Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP OOP访问全局变量_Php - Fatal编程技术网

PHP OOP访问全局变量

PHP OOP访问全局变量,php,Php,我有两个php文件。第一个是库,另一个是函数。问题是,如果我在类外声明变量,那么我会得到一个错误,称为unidentified variable。需要帮助,请提前感谢 lib.php class test{ public function __construct() { $this->_link = mysql_connect('localhost','root',''); mysql_select_db('test_db', $this-&

我有两个php文件。第一个是库,另一个是函数。问题是,如果我在类外声明变量,那么我会得到一个错误,称为unidentified variable。需要帮助,请提前感谢

lib.php

class test{
    public function __construct()
    {
        $this->_link = mysql_connect('localhost','root','');
        mysql_select_db('test_db', $this->_link);
    }
    public function query($sql)
    {

    }
}
include_once('lib.php');
$lib = new test();

function testFunction(){
    $lib->query($sql);
}
Function.php

class test{
    public function __construct()
    {
        $this->_link = mysql_connect('localhost','root','');
        mysql_select_db('test_db', $this->_link);
    }
    public function query($sql)
    {

    }
}
include_once('lib.php');
$lib = new test();

function testFunction(){
    $lib->query($sql);
}

问题是变量
$db
未识别,我不想为每个函数键入
$lib=new test()
。提前感谢。

使用从每个函数内部访问变量

function whatever($bar) {
    global $lib;
    $lib->foo($bar);
或者将$lib作为参数传递

function whatever($lib, $bar) {
    $lib->foo($bar);
Function.php

include_once('lib.php');
$lib = new test();

function testFunction()
{
    global $lib;
    $lib->query($sql);
}
您需要使用关键字将变量标记为全局变量


这应该谨慎使用,因为过度使用globals表示程序设计不好

您确实需要正确地缩进代码。混合制表符和空格是一个非常糟糕的主意。此外,您的代码还包含语法错误,例如,
class
定义中缺少类名。请不要在此处发布包含语法错误的代码<代码>mysql*现在已不推荐使用。请查看PDO或mysqli。如果您正确执行OOP,则不需要任何全局变量。对不起,先生,类的名称是test,我忘了将其放入XD。如何调用变量$db=new test(),以便函数能够识别它。这就是调用。可以帮助你理解。