2

I do not understand the rationale behind the different treatment of variable assignment between global context and class context:

$var1 = "a" . "b"; # PHP syntax o.k.

class myClass {
    private $var2 = "a" . "b"; # PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';'
}

P.S.: visibility of property (private/protected/public) doesn't play a role.

2
  • 1
    Read php.net/manual/en/language.oop5.properties.php Commented May 9, 2013 at 8:54
  • 1
    This has been asked a million times before, but this question is finally so nice and to the point that I favor it as the canonical question/answer to this issue. Commented May 9, 2013 at 9:00

2 Answers 2

5

It's not a "variable assignment in class context". private $var declares a property for the class, and you're additionally giving it a default value. You're declaring the structure of the class here, which is not the same as a variable assignment in procedural code. The class structure is parsed by the parser and compiled by the compiler and the default value for the property is established in this parsing/compilation step. The compiler does not execute any procedural code; it can only handle constant values.

As such, you cannot declare class properties with default values which need evaluation, because the part of PHP that handles the declaration of classes, the parser/compiler, does not evaluate.

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

1 Comment

Note that some simple expressions are slated to be supported in an upcoming version of PHP.
3

Quoting from the PHP docs (my emphasis)

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.

Instead, define values in the constructor if they're dependent on any evaluation.

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.