Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a class constant into a class attribute in PHP?

Here's the code that won't work :

class MyClass
{
    const myconst = 'somevalue';

    private $myvar = array( 0 => 'do something with '.self::myconst );
}

Seems that class constants are not available at "compile time", but only at runtime. Does anyone know any workaround ? (define won't work)

Thanks

like image 764
Antoine Avatar asked Feb 04 '23 00:02

Antoine


1 Answers

The problem in your class declaration is not that you are using a constant, but that you are using an expression.

Class member variables are called "properties". (...) They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this 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.

This simple declaration, for example, will not compile (parse error):

class MyClass{
    private $myvar = 3+2;
}

But if we alter your class declaration to use the simple constant, rather than a string concatenated with that constant it will work as expected.

class MyClass{
    const myconst = 'somevalue';
    public $myvar = array( 0 => self::myconst );
}

$obj = new MyClass();
echo $obj->myvar[0];

As a work-around you could initialize your properties in the constructor:

class MyClass{
    const myconst = 'somevalue';
    public $myvar;

    public function __construct(){
        $this->myvar = array( 0 => 'do something with '.self::myconst );
    }
}
$obj = new MyClass();
echo $obj->myvar[0];

I hope this helps you,
Alin

like image 130
Alin Purcaru Avatar answered Feb 05 '23 16:02

Alin Purcaru