gpt4 book ai didi

php - 为什么不能使用 property 而不是 __construct?

转载 作者:行者123 更新时间:2023-12-04 06:49:53 24 4
gpt4 key购买 nike

开始使用 oop

为什么:

class user 
{
private $pdo;

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

...
}

这工作正常。但是这个:
class user 
{
private $pdo = singleton::get_instance()->PDO_connection();

...
}

这不起作用。错误 parse error, expecting ','' or ';'' 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com