2

Why can I assign

$tmpPath = DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;

within a class method but get an PHP Parse error when I trie to assign it to a protected class variable like this:

protected $_tmpPath = DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;

Here is the error log:

PHP Parse error: syntax error, unexpected '.', expecting ',' or ';' in ...

1 Answer 1

3

Property values must be a single, constant value, not an expression.

Unless you're using PHP5.6 in which case the code you have there is perfectly allowed.

But until you do, the typical workaround is to assign the value to it in the class's constructor.

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

6 Comments

So by single value you mean anything which has not to be evaluated to a value? So for example concatenating of stings is single value or expression then? Couldn't find a proper definition.
Concatenation is an expression.
The doc says The simplest yet most accurate way to define an expression is "anything that has a value". php.net/manual/en/language.expressions.php However that conflicts with this answer, because surely 'abcd' is also an expression and is allowed for property values PHP<5.6. Also constants are allowed for property values PHP<5.6 (EG public foo = DIRECTORY_SEPARATOR;)
This is what the doc says about initializing properties: php.net/manual/en/language.oop5.properties.php 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. So where NietTheDarkAbsol talks about 'single values' vs 'expressions', he should say 'a constant'
@nl-x Edited, is that better?
|

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.