gpt4 book ai didi

类属性中的 PHP 函数调用

转载 作者:可可西里 更新时间:2023-10-31 23:22:21 25 4
gpt4 key购买 nike

为什么我不能在 PHP 中执行此操作?其中 Database 是一个单例类,getInstance() 返回一个 PDO 对象。

<?php

class AnExample
{
protected static $db = Database::getInstance();

public static function doSomeQuery()
{
$stmt = static::$db->query("SELECT * FROM blah");
return $stmt->fetch();
}
}

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

http://php.net/manual/en/language.oop5.static.php

为什么?!

最佳答案

http://php.net/language.oop5.properties

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.

重要的是

that is, it must be able to be evaluated at compile time

表达式是在运行时求值的,因此不可能使用表达式来初始化属性:它们根本无法求值。

关于类属性中的 PHP 函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14665097/

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