When PHP declares a member variable, you may encounter the following problems.
This is a mistake made by programmers who have migrated data from Java. It took a lot of time to solve the tragedy.
Situation
Let's take a look at it and define a member variable correctly. If we have learned other languages, we will soon find that we are very familiar with such a structure.
A simple declaration of member variables
Class Test {
Public $ a = "AB ";
}
Next, the defined string is long and needs to be spliced by string. If you change the name to this one, splice AB and cd together, and an error is reported, indicating a syntax error.
Incorrect concatenation of strings
<? Php
Class Test {
Public $ a = "AB". "cd ";
}
$ T = new Test ();
Echo $ t->;
?>
An error occurs.
Parse error: syntax error, unexpected '.', expecting ',' or ';' in.../test. php on line 4
Maybe you have seen such a concatenated string and can run it correctly.
You can concatenate strings in the method to work properly.
$ Str = "AB". "cd ";
Echo $ str;
And if you know that the Java language declares member variables, it's okay to know the definition.
Concatenate member variable strings in Java
Class Test {
String str = "AB" + "cd ";
}
From the Java style to the PHP style, it is a cup of cake. It's totally wrong. It's okay to look at defining a string in php, but an error is reported in the member variable.
Reason-explanation
Later.
Static variables do not run a value assignment expression. They can only use literal and const.
Similarly, the variables in the attribute can be initialized, but the initialization value must be a constant. Here the constant refers to the value that PHP scripts can obtain during the compilation phase, the value can be evaluated without running information. That is, only simple types (string, integer, array, etc.) can be used for member initialization, and functions and operators are not allowed. See http://php.net/manual/zh/language.oop5.properties.php for details
In addition, using var to declare a new version of the member variable is obsolete. If you see this in the code, never learn it like this.
Solution
Use the define method.
Define ('str', "AB". "cd ");
Class Test {
Public $ a = str;
}
$ T = new Test ();
Echo $ t->;