Cannot set variable in class equal to a function

2019-08-08 17:32发布

问题:

I started today with learning object oriented PHP programming and I am struggling with the following problem:

I can set a variable equal to for example 10:

class exampleClass {
   private $number = 10;
}

But I cannot set it equal to a function which returns 10:

class exampleClass {
   private $number = exampleFunction();
}

回答1:

You can't set class properties directly as expressions:

Invalid:

class Test {
    protected $blah = 1 + 1;
}

Instead set it in the class construct:

class Test {
    protected $blah;

    public function __construct() {
        $this->blah = 1 + 1;
    }
}