There are two ways to work with class variables. 1. The variable must be publicly available, such as:
class Person { public $isAlive = true; public static $firstname; public $lastname; public $age; } Person::$firstname = "John"; echo Person::$firstname;
2. access to a variable through a class object
class Person { public $isAlive = true; public $firstname; public $lastname; public $age; } $person->firstname = "John"; echo $person->firstname;
By the way, PHP can create an object by itself php 5.5. Your code is not crashing. It just gives a warning: Warning: creating a default object from an empty value in ...
So WHY? This is how PHP works with memory. In the first case, static means that php has already allocated memory for the variable, and you can work with it. The second case. Using the NEW command, you give the php command to allocate memory and load the class into it. So, after creating the class, you have access to var.
In the third case, PHP calls the new person himself and gives you a warning. I do not recommend relying on the default php behavior. ALWAYS create an object explicitly
source share