静态方法 - 调用函数

时间:2013-05-16 19:23:49

标签: php

echo System\Core\Request::factory()->execute();

首先调用factory(),然后调用构造函数,并在此处执行execute()。它当然按预期工作。

Request类包含几个NON-STATIC属性。我在工厂方法中设置了所有这些。像这样:

public static function factory()
{
   if(! Request::$initial)
   {
      $request = Request::$initial = Request::$current = new Request();
      $request->foo = 'bar';
   }
   else
   {
      Request::$current = $request = new Request();
      $request->foo = 'aaa';
   }
   return Request::$current;
}

接下来是构造函数:

public function __construct()
{
   echo $this->foo; // displays empty string
   echo Request::$current->foo; // trying to get property of non-object
}

发生了什么事?

1 个答案:

答案 0 :(得分:2)

在设置foo之前调用构造函数,因为在实例化请求后在工厂中设置它。

public static function factory()
{
   if(! Request::$initial)
   {
      // constructor is called as part of this line
      $request = Request::$initial = Request::$current = new Request();

      // foo is set AFTER the constructor is called
      $request->foo = 'bar';
   }
   else
   {
      // constructor is called as part of this line
      Request::$current = $request = new Request();

      // foo is set AFTER the constructor is called
      $request->foo = 'aaa';
   }
   return Request::$current;
}