开始使用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/