【发布时间】:2023-04-03 17:15:01
【问题描述】:
我正在尝试在类中创建一个方法,该方法将实例化当前所在的类。但我还需要该方法中的该方法才能在所有扩展类中正常工作。正如我从this thread 中了解到的,在此任务中使用self 关键字并不好。所以显而易见的选择是使用 static 关键字。
但是,我遇到了同样有效的不同方法。
例子:
class SimpleClass
{
private $arg;
public function __construct( $arg ){
$this->arg = $arg;
}
public function getArg(){return $this->arg;}
public function setArg($arg){$this->arg = $arg;}
public function staticInstance()
{
return new static( $this->arg );
}
public function thisInstance()
{
return new $this( $this->arg );
}
public function selfInstance()
{
return new self( $this->arg );
}
}
class ExtendedClass extends SimpleClass
{
}
$c1 = 'SimpleClass';
$c2 = 'ExtendedClass';
$inst1 = new $c1('simple');
$inst2 = new $c2('extended');
$static_instance_1 = $inst1->staticInstance();
$this_instance_1 = $inst1->thisInstance();
$self_instance_1 = $inst1->selfInstance();
$static_instance_2 = $inst2->staticInstance();
$this_instance_2 = $inst2->thisInstance();
$self_instance_2 = $inst2->selfInstance();
echo "SimpleClass Instances\n";
echo get_class($static_instance_1);
echo get_class($this_instance_1);
echo get_class($self_instance_1);
echo "ExtendedClass Instances\n";
echo get_class($static_instance_2);
echo get_class($this_instance_2);
echo get_class($self_instance_2);
从这个例子中我可以看到,staticInstance 和 thisInstance 都产生“正确”的结果。还是他们?
谁能解释这两种方法之间的区别,哪一种是“正确”的。
【问题讨论】:
-
不确定,但是,只要您使用
new,就没有区别。使用clone并将实例存储在自身中时,这变得很有趣。 -
我对静态与自我的了解是,如果您要从扩展类的对象实例调用它继承的方法,例如,创建一个
new static ...,它将创建扩展类的新实例。如果它使用了self,它将创建一个新的父实例(因为该方法存在于父中) -
关于静态和自我困境的一切都在我在问题的第一段中引用的链接中进行了解释。我的困境是在 $this 和 static 之间 :)
标签: php instance instantiation