Thomas
Thomas

Reputation: 2367

php oop variable scope

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.

Upvotes: 1

Views: 2257

Answers (3)

blockhead
blockhead

Reputation: 9705

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

Upvotes: 0

deceze
deceze

Reputation: 522016

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.

Upvotes: 2

gnud
gnud

Reputation: 78518

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.

Upvotes: 5

Related Questions