PHP function call in class property

后端 未结 3 578
孤独总比滥情好
孤独总比滥情好 2020-12-02 02:18

Why can\'t I do this in PHP? Where Database is a singleton class and getInstance() returns a PDO object.



        
相关标签:
3条回答
  • 2020-12-02 02:51

    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.

    0 讨论(0)
  • 2020-12-02 02:52

    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.

    0 讨论(0)
  • 2020-12-02 02:53

    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.

    0 讨论(0)
提交回复
热议问题