1

Why I can't use separators (.) in variables inside a class?

class Object(){
    public $var  = "Hello"."World";
    # Or
    public $test = "Hello";
    public $var2 = $this->test."World";
}

This code gives me this error:

Parse error: syntax error, unexpected '.', expecting ',' or ';' in test.php on line 2

And how should I do it?

1 Answer 1

4

Because you cannot declare class properties with variable expressions. That means you cannot use any arithmetic operators + - * / or the concatenation operator ., and you can't call functions. Out of your three lines, only $test should work; the other two will give you errors.

If you need to build your strings dynamically, do it in the constructor.

class Object {
    public $test = "Hello";
    public $var2;

    public function __construct() {
        $this->var2 = $this->test . "World";
    }
}

By the way, . is not a "string separator". It's the concatenation operator. You use it to join strings, not separate them.

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

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.