Reputation: 691
When the declaration of a PHP class variable we cannot perform any expressions, e.g.:
class A
{
$a = 10 + 5;
}
only we can just provide constants e.g.:
class A
{
$a = 100;
}
Can anybody knows why its like that?
Upvotes: 20
Views: 14250
Reputation: 1070
When declaring a class variable in PHP OOP, they are called class member variables or class properties. The reason why we cannot assign values or perform any expression or calculation is that You're declaring the structure of the class here, which is not the same as a variable assignment in procedural code. The OOP PHP class structure is parsed by php Parser and Compiled, while doing this operation the Compiler does not execute any procedural code. It can only handle constant values.
As you already know the following will not work and one gets syntax error.
class A
{
$a = 100;
}
But you can achieve the same thing by using constant in class like this.
class A
{
const a = 100;
}
echo A::a;
If you need to do operations you do this by using methods or even class constructor if needed.
Upvotes: 2
Reputation: 29
Well if it has something to do with initializing a new database name via "file.txt" which you refer through a certain path, what I did to resolve such problem is this:
class A
{
private static $a = "";
private function __construct()
{
$a = //Code to get the value and initialize it.
}
}
Upvotes: -1
Reputation: 68466
That is because expression is not allowed as field default value. Make use of constructors to initialize the variables instead.
I suggest you do like this..
class A
{
public $a;
function __construct()
{
return $this->a = 10 + 5;
}
}
$a1 = new A;
echo $a1->a; //"prints" 15
Upvotes: 31
Reputation: 1370
You can only perform expressions on Properties in constructor
or other member functions
of the class.
Note that, you can initialize value to property outside of constructor and member functions too. But It's impossible to make the expression. The best practice is to initialize and perform expressions in Constructor and member functions of the class.
Upvotes: 1
Reputation: 1357
You cannot use statement or function, just a scalar value. This is because class variables are initiated in compile time (before runtime). Class constructor should be used to initiate property with statement/function.
Upvotes: 18