Robbert
Robbert

Reputation: 1330

Cannot set variable in class equal to a function

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();
}

Upvotes: 1

Views: 550

Answers (1)

AlpineCoder
AlpineCoder

Reputation: 627

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

Upvotes: 1

Related Questions