I am trying to create a method inside class, that will instantiate class that is currently in. But I would also need that from this method to work correctly in all extended classes. As I have learned from this thread, it's not good to use self
keyword for this task. So obvious choice would be using static
keyword.
But, I've come across different method that also works.
Example:
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);
As I can see from this example, both staticInstance
and thisInstance
produce "correct" results. Or do they?
Can someone explain difference between these two methods and which one is "correct" one.