php oop variable scope

陌路散爱 提交于 2019-12-11 13:24:20

问题


So I have a class.. In its constructor I include the code which connects me to my database via the mysqli extension:

class MyClass
{
    public function __construct()
    {
        include("dbconnect");
    }
}

dbconnect looks like this:

$host = "localhost";
$user = "user";
$pass = "123";
$database = "myDatabase";

$mysqli = new mysqli($host, $user, $pass, $database);
$mysqli->set_charset('utf8-bin');

Now to my problem: Since mysqli can be used OOP-Style, how do I get access to the variable in MyClass?

function doIt()
{    
    $query = "SELECT * FROM myTable";    
    $result = $mysqli->multi_query($query);
}

A call to this function results in

Notice: Undefined variable: mysqli in ... on line ... Fatal error: Call to a member function multi_query() on a non-object in ... on line ...

So it seems the scope of the variable is not right. Does anyone know how to fix this? It would be best if MyClass would not need an extra reference or something to mysqli, since I would like to keep it seperated.


回答1:


The $mysqli variable is only available inside the scope of the constructor. Change your constructor like so:

class MyClass
{
    public function __construct()
    {
        include("dbconnect");
        $this->mysqli = $mysqli;
    }
}

Now you can use $this->mysqli in other methods on that object.




回答2:


The variable has the same scope as any other variable inside a function: it is only valid inside the function. As soon as the function returns, it's gone. If you want to "persist" a variable for other function in the class, make it a Class member:

class MyClass {
    var $member = null;

    function foo() {
        $localVar = $this->member;
        $this->anotherMember = 'bar';  // $anotherMember is now available for other functions
    }
}

Reusing code via an include is not good precisely because it doesn't give you any control over how the variables will be used. I'd think about restructuring the thing, like making a function that establishes the DB connection, then returns the DB handle.




回答3:


What you're looking for is the "global" keyword. In general, though, I would avoid globals and rethink your design.



来源:https://stackoverflow.com/questions/2323242/php-oop-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!