简体   繁体   English

将公共静态函数的返回值分配给私有变量

[英]Assign a public static function's return value to a private variable

There are two classes: 有两类:

class Db {
    public static function getConnection () {
        /*Initialize parameters*/
        $db = new PDO (...);
        return $db;
    }
}

Class Db initializes and returns a PDO object. 类Db初始化并返回PDO对象。

Then I want to do following in another class: 然后我想在另一堂课中做以下事情:

class User {
    private $db = Db::getConnection();
    ....
}

Why am I getting an error here: 为什么我在这里出现错误:

private $db = Db::getConnection();

Without knowing the error, it's hard to say, but I'd guess is because you can't do that there, try this. 不知道错误,很难说,但是我猜是因为您不能在那做,请尝试一下。

class User {
    private $db = null;

    function __construct(){
        $this->db = Db::getConnection();
    }

    public function getFriends(){
        return $this->db->query('SELECT * FROM friends');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM