在PHP中调用可选方法的最佳方法?

时间:2014-02-17 08:23:02

标签: php methods

哪种方式会更好,

一个。检查是否存在要调用的方法:

class Foo extends Bar {
    public function __construct() {
        . . .
        if (is_callable([$obj, 'myMethod'])) {
            $obj->myMethod();
        }
        . . .
    }
}

B中。在父类中有一个空白方法

class Bar {
    protected function myMethod() {}
}

class Foo extends Bar {
    public function __construct() {
        . . .
        $obj->myMethod();
        . . .
    }
}

1 个答案:

答案 0 :(得分:1)

你永远不需要猜测对象是否有方法。您需要知道该对象是否具有基于其类型的方法。你应该不检查它的类型是什么,通常,你应该有一个理智的类层次结构,并在适当的地方需要正确的类型:

function foo(MyType $bar) {
    ...
}

此函数需要类MyType的对象,您知道MyType可以做什么和不能做什么。所以不需要检查任何东西。

但是,在某些情况下,您可能需要手动检查,在这种情况下会有instanceof

if ($foo instanceof MyType) {
    ...
}

如果该特定方法不适合特定的类层次结构,则为其创建一个接口:

interface MyMethodInterface {
    public function myMethod();
}

class Foo implements MyMethodInterface {

    public function myMethod() {
        ...
    }

}

然后对MyMethodInterface进行上述类型检查。