4

为什么我不能在 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();
    }
}

与任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许表达。因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象。

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

为什么?!

4

3 回答 3

4

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.

于 2013-02-02T18:36:40.900 回答
0

即时通讯 ;)

请参阅 PHP 文档中第一段的最后一句以获取属性http://www.php.net/manual/en/language.oop5.properties.php

这个声明可能包括一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖于运行时信息才能被评估。

于 2013-02-02T18:36:33.770 回答
0

You can't execute code to produce the value of a static variable as, by definition, static variables are affected at compile time, see :

Getting the run-time value of a variable, or calling a function (run-time too) can't be done at compile-time to they cannot be affected to static variables.

于 2013-02-02T18:57:16.937 回答