1
    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?

Hamza
  • 11
  • 2
  • 4
    You need to understand what static means before you use it. This output is expected – John Conde Dec 30 '20 at 14:45
  • Does this answer your question? [What's the difference between public STATIC and public function in php?](https://stackoverflow.com/questions/45476515/whats-the-difference-between-public-static-and-public-function-in-php) – Simone Rossaini Dec 30 '20 at 14:46
  • The output is more than just expected - saving state across calls is the *entire point* of a static class property. If you don't want that, then a static property is not the right answer. – iainn Dec 30 '20 at 14:57

1 Answers1

1

If your expected output is:

Create New Object
Create New Object
Create New Object
Create New Object

Then what you want is:

class User
{
    public function __construct() {
       echo "Create New Object<br/>";
    }
    public static function get()
    {
       return new self();
    }
}

$user1 = User::get();
$user2 = User::get();
$user3 = User::get();
$user4 = User::get();

// or

$user1 = new User();
$user2 = new User();
$user3 = new User();
$user4 = new User();

As people pointed out in the comments, the static flag indicates that there is only one instance of a variable across the entire class definition. If you want to create a new instance of the User::$User property, then there's no point in having it attached as a static variable to the class definition.

Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30