aurelienC aurelienC - 3 months ago 26
PHP Question

PHP - Inheritable copy method

here is my situation :

I have a class that is inherited by a dozen of others, in this class I have a copy method which returns a copy of itself.

I can use this method in the inheriting class but, obviously, the method always return an instance of the super class, not the one which inherit from it.


I would like my copy method to return an instance of the ihneriting class.



BaseEntity.php :


class BaseEntity
{
protected $id;
protected $name;
protected $active;
protected $deleted;

// ...

public function copy()
{
$copy = new BaseEntity();

$copy->id = $this->id;
$copy->name = $this->name;
$copy->active = $this->active;
$copy->deleted = $this->deleted;

return $copy;
}
}


User.php :


class User extends BaseEntity
{
// ...
// Properties are the same as BaseEntity, there is just more methods.
}

Answer

One more way to achieve what you want:

<?php
class BaseEntity
{
    protected $id;

    public function copy()
    {
        $classname = get_class($this);
        $copy = new $classname;

        return $copy;
    }
}
class Test extends BaseEntity
{

}

$test = new Test;
$item = $test->copy();
var_dump($item); // object(Test)