Mr Coder
Mr Coder

Reputation: 8186

Initiating/declaring constants in PHP class with concatenation

class Foo 
{

const MY_CONST = 'this is ' . 'data' ;  //use of concatenation

public function __construct() {}

}

This gives error :

syntax error, unexpected '.', expecting ',' or ';'

Then how I am supposed to use concatenation with constants?

Upvotes: 1

Views: 987

Answers (2)

Boris Guéry
Boris Guéry

Reputation: 47585

Constants, should be, constants, it's why you can't work with expression here.

I don't advise you the runkit_constant_add() as it transforms a constant in a variable (or kind of) which is not the case and can be confusing.

To resolve this issue, I usually "wrap" my constant in a protected array. Use the constant to be used a key of an array, to have more complex expressions.

class Foo {
    const YEAR = 'year';
    const DAYS = 'days';

    protected $_templates = array(
        self::YEAR => 'There is %s' . 'year ago',
        self::DAYS => 'There are ' . '%s' . 'days ago',
    );

    public function getMessage($key)
    {
        return $this->_templates[$key];
    }
}

And let you use:

$foo = new Foo();
$foo->getMessage(Foo::YEAR);

Upvotes: 1

mario
mario

Reputation: 145482

You cannot assign expressions there. You can only define plain values in a class definition.

The only workaround here would be to use runkit_constant_add() in the constructor, which is not available on all PHP setups.

Upvotes: 3

Related Questions