0

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.

Leo Galleguillos
  • 2,429
  • 3
  • 25
  • 43
  • 1
    If the answer is "no, php can't do that partially due to unintended adverse side effects", I would be glad to accept the answer. On the other hand, I was contemplating whether `static::` could instantiate the object using the desired namespace, but `static::` seem to apply to class properties only, and not aliases. – Leo Galleguillos Feb 23 '20 at 19:02
  • It's an interesting observation. I've re-worked the comment as an answer. – tadman Feb 23 '20 at 19:04
  • Never tried, but is it possible to pass fully qualified class name as a parameter for instantiation? – nice_dev Feb 23 '20 at 19:17
  • Yes, there are many ways to instantiate using the desired class. – Leo Galleguillos Feb 23 '20 at 20:09

1 Answers1

1

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.

tadman
  • 208,517
  • 23
  • 234
  • 262