...

View Full Version : Cannot concatinate a variable to a protected variable?



phantom007
01-22-2012, 08:11 AM
Hi

why does the following syntax generate an error:




<?php
class Foo
{
protected $my_static = $var . 'foo';
}


Parse error: syntax error, unexpected T_VARIABLE in /var/www/test.php on line 4

bacterozoid
01-22-2012, 11:20 AM
It's not because you can't concatenate stuff, it's because you can't use a variable there. When you instantiate that class, it has no idea what $var even is.

Something like this is probably what you want:


class Foo {

protected $foo;

function __construct($var) {
$this -> foo = $var . 'bar';
}

}

phantom007
01-22-2012, 02:55 PM
That solved my problem.

Many thanks sir.

Fou-Lu
01-22-2012, 02:59 PM
This description is a little inaccurate, though on the right lines. It doesn't matter if the scope was to include another member, the problem is that a default value to a member property cannot be an expression at all. Only constant data is allowed, not even a private $var = 4 + 4; is allowed.
As pointed out, a simple constructor gets around this problem completely. You don't even need to accept anything:


public function __construct()
{
$this->foo = 4 + 4;
}


This is why I recommend initializing all variables within the constructor instead of the member signature. Since I like to keep it consistent, I won't split the two up, but more often than not a member property is dynamic in nature.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum