Reputation: 4772
I have a class Foo in its namespace Bar:
namespace Bar;
class Foo
{
public function main()
{
// This will be Bar\Biz
return new Biz();
}
}
The main() method returns class Bar\Biz
I would like to extend this class with no changes other than returning MyBar\Biz rather than Bar\Biz. I can do it like this:
namespace MyBar;
class myFoo extends Bar\Foo
{
public function main()
{
// This will be MyBar\Biz
return new Biz();
}
}
Method main() is identical to the parent method. It just happens to run in a different namespace. This works.
However, main() is a long and complex method and I do not want to duplicate all its code and have to keep my copy synchronized with the source class that I am overriding. Is there a way to do this without having to duplicate the code?
I'm on PHP5.4, but I would be interested if there are solutions for later versions of PHP if it cannot be done in 5.4 (I am aware there is some kind of "import" in 5.6 that may be a solution?)
Upvotes: 0
Views: 95
Reputation: 190905
Extract the result into its own function and override that instead.
namespace Bar;
class Foo
{
public function main()
{
// lots of logic
return create();
}
protected function create()
{
return new Biz();
}
}
namespace MyBar;
class myFoo extends Bar\Biz
{
protected function create()
{
return new Biz();
}
}
Upvotes: 1