user2130296
user2130296

Reputation: 129

Static member in PHP?

I have an example as below:

class Application{

    private static $_app;
    public static function setApplication($app)
    {
        self::$_app = $app;
    }
    public static function getApplication()
    {
        var_dump(self::$_app);
    }
    public static function createDemoApplication($config)
    {
        return self::createApplication("Demo",$config);
    }
    public static function createApplication($class,$config)
    {
        return new $class($config);
    }
}

class Demo{

    public function __construct($config)
    {
        Application::setApplication($this);
        Application::getApplication();
        if(is_array($config))
        {
            foreach($config as $key=>$value)
            {
                $this->$key=$value;
            }

        }
        Application::getApplication();
    }

    public function getValue($key)
    {
        return $this->$key;
    }
}

$config = array('var1' => "test 1","var2" => "test 2");
echo Application::createDemoApplication($config)->getValue("var1");

As the result:

When the code Application::getApplication(); is performed in the first place, it returns null. However, this one in the second place return ["var1"]=> string(6) "test 1" ["var2"]=> string(6) "test 2"

I quite dont understand what happened because I assigned $this to the $_app variable first and then I set $this with new set of key/value.

Could you explain to me about this matter. Thank you

Upvotes: 0

Views: 54

Answers (1)

jd182
jd182

Reputation: 3260

When I run this code I get the following (I added the comments for clarity):

// Output from first Application::getApplication();
object(Demo)[1]

// Output from second Application::getApplication();
object(Demo)[1]
  public 'var1' => string 'test 1' (length=6)
  public 'var2' => string 'test 2' (length=6) 

// Output from echo Application::createDemoApplication($config)->getValue("var1");
test 1

It seems to be working correctly to me. The first time you call Application::getApplication() the object has been created but has no properties.

You then assign the properties in your foreach loop.

When you next call Application::getApplication() it shows the properties you have assigned.

Finally you echo out the value of 'var1'.

Upvotes: 1

Related Questions