【问题标题】:How do I avoid having to pass my connection variable as a function parameter in a class?如何避免将连接变量作为类中的函数参数传递?
【发布时间】:2018-10-04 19:56:25
【问题描述】:

我对 OOPS PHP 还很陌生,我似乎在处理一些基本问题时遇到了麻烦。

我正在尝试在构造函数中设置 $connection 变量,然后让该变量在整个类中可用,而无需将其作为参数显式传递给每个函数。

如果我将 $connection 参数作为参数传递给后面的函数,脚本将按预期工作,但似乎 $connection 变量在整个类中不可用,因为我认为它应该是.. . 如果我不通过它,我会得到一个“未定义的变量:连接”错误。

任何帮助将不胜感激。谢谢!

class ClsVREQDataAccess
{

protected $connection;

public function __construct() {

    $connection = $this->ConnectToLNSODB();

    $this->InitializeNewVREQ($connection);
}


public function InitializeNewVREQ($connection) {

    ... Do stuff to set up query ...

            $rst = $connection->prepare($strSQL);
            $rst->execute($params);

    ... Do other stuff ...

}

    ... more functions, incl the above referred-to ones ...

【问题讨论】:

    标签: php oop constructor scope


    【解决方案1】:

    您应该在任何地方使用$this->connection 来引用您在构造函数中分配的对象属性。

    class ClsVREQDataAccess
    {
    
    protected $connection;
    
    public function __construct() {
    
        $this->connection = $this->ConnectToLNSODB();
    
        $this->InitializeNewVREQ();
    }
    
    
    public function InitializeNewVREQ() {
    
        ... Do stuff to set up query ...
    
                $rst = $this->connection->prepare($strSQL);
                $rst->execute($params);
    
        ... Do other stuff ...
    
    }
    

    【讨论】:

    • 嗯,这似乎不起作用。同样的错误。 “注意:未定义变量:第 107 行 .../Class_VREQDataAccess.php 中的连接 致命错误:未捕获的错误:无法访问 ...中的空属性
    • 第 107 行是什么?
    • $this->$connection = new PDO("sqlsrv:Server=".$serverName.";Database=DBNAME;ConnectionPooling=0", "USERNAME", "PASSWORD");跨度>
    • $this->connection 不是$this->$connection
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多