PHP:在具体类的父类中,在继承方法中键入提示类的最佳方法是什么?

时间:2021-08-07 23:24:14

Yeah I know, that title is a mouthful :)

是的,我知道,这个头衔是满口的:)

Code will make this way more digestible:

代码将使这种方式更容易消化:

namespace AbstractLevel;    

abstract class Bar 
{
    public function addFoo(Foo $foo)
    {
        $this->foo = $foo;
    }
}

namespace AbstractLevel\ConcreteLevel;

class Bar extends \AbstractLevel\Bar
{
    public function addFoo(Foo $foo)
    {
        parent::addFoo($foo);
    }
}

The above code should receive a runtime notice when instantiating the AbstractLevel\ConcreteLevel\Bar class because the addFoo() method is typehinting for a different class than its parent's method of the same name.

上面的代码在实例化AbstractLevel \ ConcreteLevel \ Bar类时应该收到运行时通知,因为addFoo()方法是与其父​​类同名方法不同的类的类型。

Is there any way to ensure that the AbstractLevel\ConcreteLevel\Bar::addFoo() typehints for the class AbstractLevel\ConcreteLevel\Foo instead of AbstractLevel\Foo?

有没有办法确保AbstractLevel \ ConcreteLevel \ Bar :: addFoo()类型提示类AbstractLevel \ ConcreteLevel \ Foo而不是AbstractLevel \ Foo?

1 个解决方案

#1


0  

Is there any way to ensure...

有没有办法确保......

You can add the absolute path to the typehinted class:

您可以将绝对路径添加到typehinted类:

public function addFoo(\AbstractLevel\ConcreteLevel\Foo $foo)

I'm currently not 100% sure about the keyword abstract,

我目前对关键字摘要不是100%肯定,

you might need to put it there in the first class:

你可能需要把它放在第一堂课:

abstract class Bar 
{
    public abstract function addFoo(Foo $foo)

#1


0  

Is there any way to ensure...

有没有办法确保......

You can add the absolute path to the typehinted class:

您可以将绝对路径添加到typehinted类:

public function addFoo(\AbstractLevel\ConcreteLevel\Foo $foo)

I'm currently not 100% sure about the keyword abstract,

我目前对关键字摘要不是100%肯定,

you might need to put it there in the first class:

你可能需要把它放在第一堂课:

abstract class Bar 
{
    public abstract function addFoo(Foo $foo)