why (object) NULL or new stdClass IN a php functio

2020-04-30 16:03发布

问题:

Who can explain why this returns an error:

$test = new myclass();

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

    public function addmember() {
        $this->object->member1 = 'member 1';
    }
}
$test -> addmember();

... and this is OK:

$test = new myclass();

class myclass {
    private $object = '';

    public function addmember() {
        $this->object = (object) NULL;// new stdClass();
        $this->object->member1 = 'member 1';
    }
}
$test -> addmember();

But why? Who can explain why the first example is wroing? Why I have to put the line with "(object)NULL" IN the function?

回答1:

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


标签: php class object