9

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"
);
2
  • 1
    Thanks for the quick response ManseUK. In the interest of understanding my problem a little more - what does it return? I var_dump'ed it: string(26) "/var/www/../trunk" Commented Jan 6, 2012 at 15:17
  • 1
    set $stuff value on your constructor Commented Jan 6, 2012 at 15:18

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So because __ DIR __ is the current file's location its runtime information so isn't available at compile time. Thanks Tim.
@acairns: Not exactly. PHP has the value of __DIR__ when the script is being compiled, as you can see when initialising the string like: "{__DIR__} value". How you're accessing the magic constant is the only difference here, where one is seen as a constant expression and the other is not.
3

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

Comments

0

Set $stuff value on your constructor

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.