没有实际方法声明的PHP typehint专门化

时间:2011-01-29 10:36:23

标签: php

我到处都有以下代码:

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专业化?

1 个答案:

答案 0 :(得分:0)

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

class Foo { }
class Bar extends Foo { }

class Container extends Object implements \IteratorAggregate {

    public function AddObject(Foo $menu) { }

}

Container::AddObject(new Bar());