传递构造函数变量


Passing constructor variables

所以我有一个类扩展了另一个类。下面是我的代码。主要的类是Model。然后我有另一个类create_user_model扩展Method。

//Model Class//
class Model {
private $connection;
private $connstring;
public function __construct(){
$this->connection = new createConnection();         //create connection object
$this->connstring = $this->connection->connectToDatabase();
}}

然后我有我的创建用户模型扩展模型。

/// Create_User_Model///
class Create_User_Model extends Model {
private $connection;
private $connstring;
private $sql;
function __construct() {
  parent:: __construct();
}
public function create_user(){
//Want to get rid of these two lines and get $this->connstring from constructor//
$this->connection = new createConnection(); //create connection object
$this->connstring = $this->connection->connectToDatabase();
$sql = "INSERT INTO customers (first_name, last_name)
VALUES ('John', 'James')";
if ($this->connstring->query($sql) === TRUE) {
     echo "New record created successfully";
 } else {
     echo "Error: " . $sql . "<br>" . $this->connstring->error;
 }
 }
 }

注意我是如何在Create_User_Model的构造函数中构造Model的。所以现在我应该可以访问函数create_user中的变量$this->connection和$this->connstring(或者至少是我所想的),但我不知道如何访问它们。你可以看到,我必须在create_user函数中再次创建一个连接对象,然后从头创建connstring,这样就没有构造函数的意义了。我想知道如何从构造函数中获得这些信息,以便我可以在create user函数中取出前两行。希望我问的是有意义的。谢谢阅读

私有变量只能在声明它们的类中使用。受保护的变量可以在它们自己的类和任何类扩展中使用。公共变量可以从任何地方访问。

将Model中的属性从private改为protected