class User
{
private static $User;
public static function get()
{
if (empty(self::$User)) {
echo "Create New Object<br/>";
return self::$User = new User();
}
echo "Already Created<br/>";
return self::$User;
}
}
User::get();
User::get();
User::get();
User::get();
This is my code. when I run this code then output given this code is,
Create New Object
Already Created
Already Created
Already Created
But why? My expected output is,
Create New Object
Create New Object
Create New Object
Create New Object
Because when we call a static function in class then it's full newly call this class and all time it creates a new object because all time the user is empty when calling this function. but why this code saves previous class data?
If your expected output is:
Then what you want is:
As people pointed out in the comments, the
staticflag indicates that there is only one instance of a variable across the entire class definition. If you want to create a new instance of theUser::$Userproperty, then there's no point in having it attached as a static variable to the class definition.