How to use a class constant into a class attribute

2019-06-16 03:33发布

问题:

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

回答1:

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



回答2:

Note that for PHP 5.6 and above, it's possible to do so.

See https://secure.php.net/manual/en/migration56.new-features.php:

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.