我有一些代码经常看起来像这样:
private $user;
public function __construct()
{
$this->user = User::getInstance(); //singleton
}
public function methodOne()
{
return $this->user->foo();
}
public function methodTwo()
{
return $this->user->foo2();
}
public function methodThree()
{
return $this->user->foo3();
}
我想如果我将用户属性设置为实例,我可以在我的方法中重复使用一个较短的名称(虽然在这种情况下它并不是那么短)。 我也认为以这种方式做可能会节省一些资源(开始怀疑它),但当我查看其他人的代码时,我很少看到人们这样做。 他们通常只会调用:
User::getInstance()->foo();
User::getInstance()->foo2();
User::getInstance()->foo3();
有没有最佳实践可以参考?如果不是单例类,也许可以这样做?或者你永远不应该这样做?希望能得到一些澄清,谢谢。
编辑: 以防有任何误解,我只是想知道是否应该使用创建属性来存储实例的第一个示例,而不是这种方式:
public function methodOne()
{
return User::getInstance()->foo();
}
public function methodTwo()
{
return User::getInstance()->foo2();
}
public function methodThree()
{
return User::getInstance()->foo3();
}
实际上,现在我想起来了,这可能需要的代码更少,因为我不需要构造函数...
__callStatic
实现。 - mario