PHP: extending class method without inheritance

648 views Asked by At

I'm trying to separate additional functional to other files, that can be included at runtime or no. I think it's a good way to build modular architecture, but I can't find ways to implement it without inheritance. The deal is that I have base class:

class Model {
    protected $name;
    function __construct() {
        $this->name = 'default';
    }
    function getName() {
        return 'Model: ' . $this->name;
    }
}

And specific class:

class Item extends Model {
    function getName() {
        return 'Item: ' . $this->name;
    }
}

That I use through the project:

$item = new Item();
echo $item->getName();

The result will be:

Item: default

I want to change getName() behaivor at other place to get result like this:

class ExtendedItem extends Item {
    function getName() {
        return parent::getName() . ' and this is extended method';
    }
}

$extendedItem = new ExtendedItem();
echo $extendedItem->getName();

Item: default and this is extended method

But I want to achieve it without using child class, i.e without touching Item or Model class and without changing objects initialization. I suppose there will be more then one extensions like this and they will included dynamically. In what way I should searching or can you explain how to achieve this?

Thanks in advance for answers.

UPD: In other words I want to change class method behavior outside class code preserving it's default functional.

0

There are 0 answers