Can php call a static alias?

91 Views Asked by At

In php, is it possible for a method in a parent class to use an alias in a child class from within an instance of the child class?

Parent class:

class ParentClass
{
    public function getNewFoo()
    {
        return new Foo();
    }
}

Child class:

use My\Custom\Path\To\Foo;

class ChildClass extends ParentClass
{

}

Code:

$child = new ChildClass();
return $child->getNewFoo();

I would like this code to return a new instance of My\Custom\Path\To\Foo() rather than a new instance of Foo().

I realize I can store the desired path to Foo in a class property, or I can simply instantiate the desired Foo in the child class. However, both of these seem redundant considering the path is already stored in the use statement in the child class.

1

There are 1 best solutions below

0
tadman On BEST ANSWER

You're asking a lot of PHP here. It's supposed to know that your use statement is going to impact something in a completely different class, in a completely different file, just because?

If PHP did that by default it would cause a lot of very strange problems for people. Re-define the method, or as you point out, store that property in the class itself.

I think a lot of developers would expect, or at least prefer that PHP behave the way it does.

It sounds like what you need here is a factory function that can be redefined in the subclass to behave differently, or in other words, that getNewFoo() should be overridden in the subclass to use the alternate version.