Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating __DIR__ constant with a string as an array value which is a class member in PHP

Can anyone tell me why this doesn't work? It's just a crude example of what I'm trying to do somewhere else.

$stuff = array(
    'key' => __DIR__ . 'value'
);

However, this produces an error:

PHP Parse error:  syntax error, unexpected '.', expecting ')' in /var/www/.../testing.php on line 6

Also, this works:

$stuff = array(
    'key' => "{__DIR__} value"
);
like image 327
acairns Avatar asked Jan 06 '12 15:01

acairns


2 Answers

The first piece of code does not work because it's not a constant expression, as you are trying to concatenate two strings. Initial class members must be constant.

From the documentation:

[property] 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.

like image 180
Tim Cooper Avatar answered Nov 11 '22 07:11

Tim Cooper


You can't use operator in a property initialization. The workaround is to use the constructor:

public function __construct()
{
  $this->stuff = array(
        'key'   =>  __DIR__ . 'value'
  );
}

From the PHP doc:

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.

http://www.php.net/manual/en/language.oop5.properties.php

like image 45
Damien Avatar answered Nov 11 '22 08:11

Damien