Forum Moderators: coopster
In classes in php 4.3.4
var $x = "string"; // no problem
$y = "string" . " that is a bit longer";
var $x = $y; // no problem
var $y = "string" . " that is a bit longer"; // parse error (unexpected ".")
Have they fixed that in more recent versions?
Tom
In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor.
I guess they have changed this in 5. Haven't seen it yet though.
$y = "string" . " that is a bit longer";
var $x = $y; // no problem
I was hurrying. What I was actually doing was
define('MYSTRING', "string" . " that is a bit longer");
var $x = MYSTRING; // no problem
What is actually giving me problems is, in fact, a constant expression. In the following code:
define('TWO_PART_STRING', "This is a" . " two-part string.");
class myClass
{
var $x = "This is a string";
var $y = TWO_PART_STRING;
var $z = "This is a" . " two-part string.";
}
I get a parse error on the var $z line:
parse error: parse error, unexpected '.', expecting ',' or ';'
In other words, it appears that it is forbidden to concatenate strings, even when the resulting expression *is* a constant.
Tom
I was thinking that if the values were available at parse time, it would replace the strings with tokens as efficiently as possible and make a constant.
I understand that it's not allowed, but it seems sort of crazy that
define("MY_EXP", "this is" . " an expression");
...
var $x = MY_EXP;
is allowed but
var $x = "this is" . " an expression";
is not.
From a parser/compiler point of view, I would think that all expressions that evaluate to constants would be tokenized upon parsing rather than at run time, but obviously not. I suppose the problem is that in PHP quoted strings often do no evaluate to constants because of variable substitutions ("in $strings like this") so you would end up doing too many passes.
I still find this annoying. It would make more sense to me if you could only assign default values of any sort in a constructor (like in C++).