【问题标题】:PHP typehint specialization without actual method declaration没有实际方法声明的 PHP 类型提示特化
【发布时间】:2011-01-29 10:36:23
【问题描述】:

我到处都有以下代码:

class Container extends Object implements \IteratorAggregate {

    public function AddObject(Object $object, $instanceKey) {
        ...
    }

    public function AddComponent(Component $component) {
        ...
    }
}

class MenuContainer extends Container {

    public function AddComponent(Menu $component) { // <-- I'm redeclaring the method only because I need to change the typehint
        return parent::AddComponent($component);// I don't do anything useful here
    }

    public function AddObject(Menu $object, $instanceKey) { // <-- I'm redeclaring the method only because I need to change the typehint
        return parent::AddObject($object, $instanceKey); // I don't do anything useful here
    }
}

我不得不通过方法重新声明来进行 typehint 特化,因为我想防止使用我的代码的人犯错误并意外地在我的菜单中添加一些不兼容的内容。那么问题来了:有没有一种方法可以在没有实际方法重新声明的情况下进行 typehint 特化?

【问题讨论】:

    标签: php


    【解决方案1】:

    不要专门化你的方法,而是专门化你传递的类型:

    class Foo { }
    class Bar extends Foo { }
    
    class Container extends Object implements \IteratorAggregate {
    
        public function AddObject(Foo $menu) { }
    
    }
    
    Container::AddObject(new Bar());
    

    【讨论】:

    • 感谢您的回答,但我认为您错过了重点。在您的示例中,您同时允许“Container::AddObject(new Foo())”和“Container::AddObject(new Bar())”。但在我的情况下,当 Bar 被允许时,Foo 是不允许的。并且 typehints 专业化有助于做到这一点。但这迫使我创建很多鱼方法,除了“return parent::AddComponent($component);”之外没有任何用处。所以我不想在派生类中创建这些鱼方法,而是改变类型提示。
    • 这里是另一个帖子的链接:stackoverflow.com/questions/4742302/… 我已经知道如何更改 PhpDoc,现在如果可能的话,我想以同样的方式更改 Typehint
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多