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

首先调用factory(),然后调用constructor,最后调用execute()。它当然按预期工作。

请求类包含几个非静态属性。我将它们全部设置在工厂方法中。像这样:

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
}

到底是怎么回事?

4

1 回答 1

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;
}
于 2013-05-16T19:27:08.147 回答