PHP class scope

I have several classes in the application that I am currently creating, and I want to have one access to some of the other member functions, but I cannot do this.

The first class is called MySQLDB:

class MySQLDB{
public $connection;

function __construct(){
//connects to database
}

function login($username, $password){
//queries database...
}
}

Then I have a Session class:

class Session{
//variables
//constructor

function processlogin($username, $password){
$database->login($username, $password);
}

Then after that I have two class declarations:

$database = new MySQLDB();
$session = new Session();

No matter where I put these statements regarding classes, I still get the same error:

PHP Notice:  Undefined variable: database in C:\inetpub\wwwroot\cmu\include\session.php on line 52
PHP Fatal error:  Call to a member function login() on a non-object in C:\inetpub\wwwroot\cmu\include\session.php on line 52

I saw some suggestions that would suggest putting a new database object in a Session class declaration, but I want to avoid this because I use the database class in several other places in the code, and I do not want to open multiple database connections.

+3
source share
4 answers

, global:

function processlogin($username, $password){
    global $database;
    $database->login($username, $password);
}

Session:

class Session{

    private $database;

    function __construct($database){
        $this->$database = $database;
    }

    function processlogin($username, $password){
        $this->database->login($username, $password);
    }

}

:

$database = new MySQLDB();
$session = new Session($database);

, , .

+4

MySQLDB Session.

class Session{
    public $db;

    function __construct(&$db=null){
        if($db == null)
            $this->db = new MySQLDB();
        else
            $this->db = $db;
    }
    // ....
}

$database = new MySQLDB();
$session = new Session($database);
+4

. ​​, , , global:

function processlogin($username, $password){
global $database;
$database->login($username, $password);
}

, Dependecy Injection, $database processlogin() /. , , .

+2
source

$databaseIt is not defined internally processloginand is not passed as a parameter, so the function does not have access to it.

You can pass it as a constructor parameter to Session:

class Session {
    private $db;

    public function __construct($database) {
        $this->db = $database;

    public function processlogin($username, $password){
        $this->$db->login($username, $password);
    }
}

$database = new MySQLDB();
$session = new Session($database);
+2
source

All Articles