2

This code gives the error "unexpected '.', expecting ')'". Why is this invalid? I'd thought that as both parts are constant, I could concatenate them. New to PHP. Thanks.

class c {
  const HELLO = 'hello';
  public $arr = array(
    'hw' => self::HELLO . 'world'
  );
}
2
  • possible duplicate of Workaround for basic syntax not being parsed Commented Dec 21, 2011 at 2:01
  • 1
    you should accept the answer below to reward the person who helped you. :) Commented Dec 21, 2011 at 2:27

1 Answer 1

6

Class properties must have constant initial values. The concatenation of those two strings is NOT a constant value.

From the documentation:

[Property] 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.

You could put the property initialisation in your constructor:

public function __construct()
{
  $this->arr = array(
    'hw' => self::HELLO . 'world'
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I had thought it would be constant. Though I do now see the point that the operator makes it an expression.

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.