問題描述
為什么我不能在 PHP 中執行此操作?其中 Database
是一個單例類,getInstance() 返回一個 PDO 對象.
query("SELECT * FROM blah");返回 $stmt->fetch();}}
<塊引用>
與任何其他 PHP 靜態變量一樣,靜態屬性只能使用文字或常量進行初始化;不允許使用表達式.因此,雖然您可以將靜態屬性初始化為整數或數組(例如),但您不能將其初始化為另一個變量、函數返回值或對象.
http://php.net/manual/en/language.oop5.static.php
為什么?!
http://php.net/language.oop5.properties
<塊引用>類成員變量稱為屬性".您可能還會看到使用其他術語(例如屬性"或字段")來引用它們,但出于此引用的目的,我們將使用屬性".它們是通過使用關鍵字 public、protected 或 private 之一來定義的,后跟一個普通的變量聲明.此聲明可能包含一個初始化,但此初始化必須是一個常量值——也就是說,它必須能夠在編譯時進行評估,并且必須不依賴于運行時信息才能進行評估.強>
最重要的是
<塊引用>也就是說,它必須能夠在編譯時被評估
表達式是在運行時求值的,所以不能使用表達式來初始化屬性:它們根本就不能求值.
Why can't I do this in PHP? Where Database
is a singleton class and getInstance() returns a PDO object.
<?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
Why?!
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.
The important part is
that is, it must be able to be evaluated at compile time
Expressions were evaluated at runtime, so it isn't possible to use expression to initialize properties: They are simply not evaluatable yet.
這篇關于類屬性中的 PHP 函數調用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!