Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why initializing a property doesn't work?

Tags:

php

laravel

Here is my code:

class Log
{
    private $mode = config('my.log.mode');
}

but it throws syntax error ..! Why? what's wrong?

Noted that this works as well:

class Log
{
    private $mode;

    public function __construct()
    {
        $this->mode = config('my.log.mode');
    }
}

well, what's the point?!

like image 579
stack Avatar asked Aug 25 '26 16:08

stack


1 Answers

You can initialize properties with constant values only. So, you can't use config() or any other helper here.

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

http://php.net/manual/en/language.oop5.properties.php

like image 155
Alexey Mezenin Avatar answered Aug 27 '26 07:08

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!