本文介绍了method_exists 在父类 php 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 php 函数 method_exists,但我需要检查该方法是否存在于对象的父类中.
I'm trying to use the php function method_exists, but I need to check if the method exists in the parent class of an object.
所以:
class Parent
{
public function myFunction()
{
/* ... */
}
}
class Child extends Parent
{
/* ... */
}
$myChild = new Child();
if (method_exists($myChild, 'myFunction'))
{
/* ... */
}
if (method_exists(Parent, 'myFunction'))
{
/* ... */
}
if (is_callable(array('Parent', 'myFunction'))
{
/* ... */
}
但以上都不起作用.我不确定接下来要尝试什么.
But none of the above are working. I'm not sure what to try next.
感谢您的帮助!
推荐答案
在这种情况下,子类必须继承父类
Class child must extend the parent in that case
class Parent
{
public function hello()
{
}
}
class Child extends Parent
{
}
$child = new Child();
if(method_exists($child,"hello"))
{
$child->hello();
}
我相信这和 method_exists 的效果是一样的.
This would have the same effect as method_exists I believe.
function parent_method_exists($object,$method)
{
foreach(class_parents($object) as $parent)
{
if(method_exists($parent,$method))
{
return true;
}
}
return false;
}
if(method_exists($child,"hello") || parent_method_exists($object,"hello"))
{
$child->hello();
}
刚刚从 Wrikken 的帖子更新
这篇关于method_exists 在父类 php 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!