1

I come across this strange behavior of PHP, assigning string:

class a {
    public $str = "a" . 'b';
}

$obj = new a();
echo $obj->str;

never works, throws following error:

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

while using as plain PHP it works:

$str = "a" . 'b';
8
  • What's your question? I believe that's expected behaviour in PHP5 (all?) as you can't have expressions in property defaults? Commented Aug 25, 2016 at 13:55
  • 1
    Incidentally, this does work in PHP 7. Commented Aug 25, 2016 at 14:08
  • This is valid from >= 5.6 Commented Aug 25, 2016 at 14:09
  • @DarraghEnright You're right. I had to go back and check. Commented Aug 25, 2016 at 14:10
  • 1
    Possible duplicate of Initializing PHP class property declarations with simple expressions yields syntax error Commented Aug 25, 2016 at 14:12

3 Answers 3

2

You cannot perform complex assignment to variable before constructor, you can assign simple string or integer to a variable. dot is consider as function

if you have to assign them you should use constructor.

See http://www.php.net/manual/en/language.oop5.properties.php

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

1 Comment

In this case you don't need a constructor if the PHP version is >=5.6.0, this is the first documentation's example
0

The dot . operator acts as a function and you cannot declare class variables using function.

If you have an init or construct function you should initialize the variable in such function.

function __construct() {
   $this->str = 'a' . 'b';
}

3 Comments

Then probably you're using php <5.6 Check phpinfo() to see what version of php you're using
In this case you don't need a constructor if the PHP version is >=5.6.0, this is the first documentation's example
What PHP version are you using? Did you check phpinfo();? What is the output?
0

Look the documentation example.

Check your PHP version.

class a {
    public $str = 'a' . 'b';
}

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.