why (object) NULL or new stdClass IN a php function?

前端 未结 1 1890
暖寄归人
暖寄归人 2021-01-27 15:18

Who can explain why this returns an error:

$test = new myclass();

class myclass {
    private $object = (object) NULL;

    public function addmember() {
              


        
相关标签:
1条回答
  • 2021-01-27 15:51

    Expressions are not allowed in a class body definition.

    From php.net:

    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.

    For example, you can not do this:

    <?php
    class A {
        public $x = 1 + 2; // < expression
    }
    ?>
    

    But can do this:

    <?php
    class A {
        public $x;
    
        public function __construct(){
            $this->x = 1 + 2;
        }
    }
    ?>
    

    Also, you can initialize property within a class body by constant value, that does not need to be evaluated on parse process:

    <?php
    class A {
        public $x = 123; // < constant value
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题