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

magic_al
  • 1,930
  • 1
  • 18
  • 26

1 Answers1

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 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 08:09
  • 2
    Concatenation is an expression. – Niet the Dark Absol Jul 10 '14 at 08:15
  • The doc says `The simplest yet most accurate way to define an expression is "anything that has a value".` http://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 08:21
  • 1
    This is what the doc says about initializing properties: http://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 08:27
  • @nl-x Edited, is that better? – Niet the Dark Absol Jul 10 '14 at 09:07
  • @NiettheDarkAbsol A bit :) ... But still you are saying "not an expression" , while even a constant, quoted string or number is an expression, and thus is valid. Sorry for nitpicking ;) (But I had already upvoted) – nl-x Jul 10 '14 at 10:33