【问题标题】:Passing constructor variables [duplicate]传递构造函数变量[重复]
【发布时间】:2015-10-04 21:52:00
【问题描述】:

所以我有一个扩展另一个类的类。这是我的代码如下。主要类是模型。然后我有另一个类 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 的构造函数中构造模型的。所以现在我应该可以访问函数 create_user 中的变量 $this->connection 和 $this->connstring(或者至少是我想的),但我不知道如何访问它们。您可以看到我必须在函数 create_user 中再次创建一个连接对象,然后全部创建 connstring,然后再创建一个构造函数是没有意义的。我想知道如何从构造函数中获取这些信息,以便在创建用户函数中取出前两行。希望我的要求有任何意义。感谢阅读。

【问题讨论】:

    标签: php constructor extends


    【解决方案1】:

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

    将模型中的属性从私有更改为受保护。

    【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2021-02-05
    • 1970-01-01
    • 2021-05-15
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多