ImNotMike ImNotMike - 7 months ago 36
PHP Question

Constants in class property values

The following code illustrates something like the behavior I would like to use in my application.

class Test {
private $var = constant . "suffix";
private $var2 = constant . "suffix2";
// ...
private $var3 = constant2 . "suffix3";
private $var4 = constant2 . "suffix3";
// ...
private $var5 = "something else";

I have a couple of properties that all have a common beginning, a prefix. So in the interest of having that prefix more easily controllable for the entire app configuration, or should I say more centralizable in case it ever needs to change, it would be nice to have it defined only once. Like in a constant, ideally.

However, using constants in this manner is not valid syntax.

The only workaround (ish) that I can think of is going through all the properties in a
loop in the constructor and prepend the prefix to them. The drawbacks are that it requires more variables that keep track of which properties need which prefix, or don't need any at all (
in my example doesn't need one), and possibly speed.

So I am wondering if there are any other, neat, handy, or slightly hacky ways of solving this kind of a situation.


You can initialize those properties just the way you want to if you move the initialization into the class constructor:

class Test {
    private $var;
    private $var2;
    // ...
    private $var3;
    private $var4;
    // ...
    private $var5;

    public function __construct() {
        $this->var = constant . "suffix";
        $this->var2 = constant . "suffix2";
        // ...
        $this->var3 = constant2 . "suffix3";
        $this->var4 = constant2 . "suffix3";
        // ...
        $this->var5 = "something else";