Question

I have a Class that owns various properties which can be modified. All of the properties have default values defined.

class Model {
    protected $name = 'defaultName';
}

Now I would like to make it possible to change the default values globally.

I tried the following:

class Model {
    protected static $defaultName = 'defaultName';
    protected $name = self::$defaultName;
}

Unfortunately this doesn't work:

Parse error: parse error, expecting `"identifier (T_STRING)"'

So I guess it's caused by the fact that you can't use expressions for initialisations or something similar? Or is this possible without setting the property value inside the constructor?

Sorry if this is a duplicate, I couldn't find the correct answer because everything else seems to focus on initialisation of static properties while my problem is about initialising the object member.

Thanks in advance!

Was it helpful?

Solution

So I guess it's caused by the fact that you can't use expressions for initialisations or something similar?

Yes. From 5.6 onwards you could formulate it more correctly as "you can't use dynamic expressions for initialisations".

Or is this possible without setting the property value inside the constructor?

No, unless you use class constants instead of static fields; unfortunately, those have the side effect that they're accessible from outside of the class.

OTHER TIPS

class Model {
    protected static $defaultName;
    protected $name;

    function __construct(){
        self::$defaultName = 'defaultName';
        $this->name = self::defaultName;
    }
}

Yes you can not do the way you are trying, you can use __construct() to do so.

Here is the example

class Model
{
    protected static $defaultName = 'defaultName';
    protected $name = '';

    public function __construct()
    {
        $this->name = self::$defaultName;
    }

    public function getName()
    {
        return $this->name ;
    }
}

$m = new Model();
echo $m->getName();
// outputs defaultName

Try this:

class Model {
    const CONSTANT = 'my value';

    protected static $defaultName = self::CONSTANT;
    protected $name = self::CONSTANT;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top