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?
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Class Variables In the case of the Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle object has its own values for these variables, stored in different memory locations. Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
Defining Class and Declaring Objects A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With