PHP function call in class property

2019-01-12 11:27发布

问题:

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?!

回答1:

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.



回答2:

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

  • http://en.wikipedia.org/wiki/Static_memory_allocation
  • http://en.wikipedia.org/wiki/Static_variable

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.



回答3:

RTM ;)

See the last sentence of the first paragraph in the PHP documentation for properties http://www.php.net/manual/en/language.oop5.properties.php

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.