开发者

php oop variable scope

开发者 https://www.devze.com 2022-12-21 05:31 出处:网络
So I have a class.. In its constructor I include the code which connects me to my database via the mysqli extension:

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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号