在PHP中调用可选方法的最佳方法是什么?
哪条路比较好, A.检查是否存在要调用的方法:在PHP中调用可选方法的最佳方法是什么?,php,methods,Php,Methods,哪条路比较好, A.检查是否存在要调用的方法: class Foo extends Bar { public function __construct() { . . . if (is_callable([$obj, 'myMethod'])) { $obj->myMethod(); } . . . } } 或 B.在父类中有一个空白方法 class Bar { protect
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();
. . .
}
}
您不需要猜测对象是否有方法。您需要知道该对象是否具有基于其类型的方法。您不应该检查其类型,通常,您应该有一个健全的类层次结构,并要求在适当的位置使用正确的类型:
function foo(MyType $bar) {
...
}
此函数需要类MyType
的对象,并且您知道MyType
可以做什么和不能做什么。所以不需要检查任何东西
但是,在某些情况下,您可能需要手动检查,在这种情况下,会出现instanceof
:
if ($foo instanceof MyType) {
...
}
如果该特定方法不适合特定的类层次结构,则为其创建一个接口:
interface MyMethodInterface {
public function myMethod();
}
class Foo implements MyMethodInterface {
public function myMethod() {
...
}
}
然后根据MyMethodInterface
进行上述类型检查,首先什么是“可选方法”?