Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ...

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
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. –  magic_al Jul 10 '14 at 8:09
2  
Concatenation is an expression. –  Niet the Dark Absol Jul 10 '14 at 8:15
    
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;) –  nl-x Jul 10 '14 at 8:21
1  
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 Jul 10 '14 at 8:27
    
@nl-x Edited, is that better? –  Niet the Dark Absol Jul 10 '14 at 9:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.