0

我目前有一个名为 Connect 的类,代码如下:

class Connect
{
public $sqlHost='host';
public $sqlUser='user';
public $sqlPass='pass';
public $sqlDB='db';

public $db;
    public function __construct() {
        $this->db = new mysqli($this->sqlHost, $this->sqlUser, $this->sqlPass, $this>sqlDB);
    }
}
?>

我还有一个名为 TODO 的类,我想知道如何从 TODO 类调用位于 Connect 类中的 $db?

4

2 回答 2

1

imagine you have have two objects called

$connect = new Connect();
$todo = new TODO();

now 1 of 3 things can happen, You can pass the $connect object into a method of $todo or if a Connect object is a member of a TODO object, or create a new connect object.

scenario 1:

class TODO {
    public function foo($connect){
        // You can get the db object here:
        $connect->db
    }
}

$todo->foo($connect)

scenario 2:

class TODO {
    public $connect;
    public function __construct(){
        $this->connect=new Connect(); 
    }
    public function foo(){
        //get db:
        $this->connect->db;
    }
}
$todo->foo();

scenario 3:

class TODO {
    public function foo(){
        $connect = new Connect();
        $connect->db;
    }
}
于 2013-02-01T01:11:51.150 回答
0

我不确定你想要什么,但我认为这是

$connectInstance = new Connect();
$connectInstance->db...

这样您就可以访问连接对象中的 db 变量。但首先,您必须实例化对象。

于 2013-02-01T01:09:22.023 回答