【发布时间】:2011-03-12 23:29:15
【问题描述】:
我有一些代码通常看起来像这样:
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();
}
实际上现在我想这可能是更少的代码,因为我不需要构造函数...
【问题讨论】: