whitburn Posted September 28, 2015 Share Posted September 28, 2015 (edited) Apologies if this is a very simple question, as the problem highlights itself as a compiler error. I'm a self taught PHP programmer, so I'm probably misunderstanding something from the object orientated side of things - but despite some googling, it's got me stumped as to how to get around it. I came across the issue when I had to make some fixes to someone else's phpunit code. They had a protected array in a class with one of the key values set as XML text. However, I found that it needed to be converted to a SimpleXMLElement. So I tried converting using simplexml_load_string(). However, this just resulted in the syntax error: PHP Parse error: syntax error, unexpected '(', expecting ')' I didn't understand this, so I stripped down to a simple standalone example which replicates the problem: <?php class problemDemo { protected $Len = strlen('MY_TEXT'); } ?> So can anyone explain why I can't set a protected variable value within a class using a function? Is there any alternative way to get around? PS. Apologies for post subject - it should have said "CAN'T use a function when defining a protected class variable"! Edited September 28, 2015 by whitburn 1 Quote Link to comment Share on other sites More sharing options...
Solution Jacques1 Posted September 28, 2015 Solution Share Posted September 28, 2015 Initialization values of properties are evaluated at compile-time, so you can't use arbitrary expressions (you're mostly limited to constant values). To get around this, you can use a constructor to set the property value when the object is created: <?php class Demo { protected $len; public function __construct() { $this->len = strlen('MY_TEXT'); } public function getLen() { return $this->len; } } $demo = new Demo(); var_dump($demo->getLen()); 1 Quote Link to comment Share on other sites More sharing options...
hansford Posted September 28, 2015 Share Posted September 28, 2015 Class properties can only be assigned a constant value and cannot rely on run-time evaluations. So, no returning values from functions. Quote Link to comment Share on other sites More sharing options...
whitburn Posted September 28, 2015 Author Share Posted September 28, 2015 Thanks, that explains my misunderstanding I'll give it a try. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.