在所有类中访问SQL连接变量?

时间:2016-12-30 19:43:54

标签: php mysql oop

我几个月没有触及PHP,也无法访问我之前的任何项目以供参考。本质上,我有我的文件lib.php,它实例化所有对象,创建将在大多数应用程序中访问的所有变量/函数。然后通过lib.php将此文件require_once调入header.php文件。在lib中,我有一个创建MySQL PDO连接的函数

try {
    $server = array(
            'server' => 'localhost:3306',
            'database' => 'to_do_list',
            'user' => 'root',
            'password' => '',
            );
    $link = new PDO('mysql:host='.$server['server'].';dbname='.$server['database'].'',$server['user'],$server['password']);
    $link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
    echo "Error Could not connect to database";
    exit;
}

我希望可以在lib.php中实例化的所有类文件中访问此处的变量,例如$link。我怎样才能以最有效的方式做到这一点?

<?php
// Session Start
session_start();

// Link Database
// Link var created here I want to be accessible in any classes instantiated below
try {
    $server = array(
            'server' => 'localhost:3306',
            'database' => 'to_do_list',
            'user' => 'root',
            'password' => '',
            );
    $link = new PDO('mysql:host='.$server['server'].';dbname='.$server['database'].'',$server['user'],$server['password']);
    $link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
    echo "Error Could not connect to database";
    exit;
}

// Functions
// Action GET/POST/SET
function getAction()
{
    if(isset($_POST['action']))
    {
        $action = $_POST['action'];
    } else if(isset($_GET['action'])) {
        $action = $_GET['action'];
    } else {
        echo "GET/SET/POST action master failed";
    }
    return $action;
}

// Input GET/POST/SET
function inputReturn($inputName) {
    if(isset($_POST[$inputName])) {
        $inputVal = $_POST[$inputName];
    } else if (isset($_GET[$inputName])) {
        $inputVal = $_GET[$inputName];
    } else {
        $inputVal = "";
        echo "GET/SET/POST input master failed";
    }
    return $inputVal;
}

// Require classes
require_once("user.php");

// Instantiate classes
$instUser = new user;

?>

0 个答案:

没有答案