php - 为什么不能用property代替__construct?

标签 php oop

开始使用oop

为什么:

class user 
{
    private $pdo;

    function __construct()
    {
        $this->pdo = singleton::get_instance()->PDO_connection();
    }

...
}

这工作正常。但这:

class user 
{
    private $pdo = singleton::get_instance()->PDO_connection();

...
}

这不起作用。错误解析错误,需要 ','' 或 ';'' in ...

第二个变体有什么问题?

最佳答案

参见Properties第一段最后一句在 PHP OOP documentation :

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

换句话说,此语句返回的数据库处理程序不是常量值,因此在编译时不可用:

singleton::get_instance()->PDO_connection();

关于php - 为什么不能用property代替__construct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286293/

相关文章:

php - mysql : select rows from table 1 and test if rows exists in table 2

PHP 书签

php - 在 MySQL PDO 中使用带有 % 的 LIKE 时,不返回带有大写字母的行

java - 在 main 方法之前执行静态 block

java - Android/Java 中的 OOP

python - 将方法参数转发给另一个方法 - self 需要从 locals() 中弹出

php - 在 WHILE 之前拉取连接表数据

php - 无法在 PHP 中将数据发布到正文中

c# - 有关如何清理此 API 的建议

design-patterns - 您如何在领域驱动设计中使用具有工厂模式的接口(interface)?