method_存在于父类php中
我正在尝试使用 php 函数 method_exists,但我需要检查该方法是否存在于对象的父类中。
所以:
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'))
{
/* ... */
}
但是以上都不起作用。我不知道接下来要尝试什么。
感谢您的帮助!
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.
so:
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.
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果在子类中完成,method_exists 和 get_parent_class 组合起来是否也可以工作?
例如
Wouldn't method_exists and get_parent_class combined also work if done within the child class?
For instance
RobertPitt 的说法是正确的,
Child
类不是子类,除非它扩展了Parent
类。但从您的原始代码片段来看,以下内容应该是正确的:请注意,“Parent”用引号引起来,您没有将其引号括起来。将类名作为字符串传递。
RobertPitt is correct in that the
Child
class is not a child class unless it extends theParent
class. But from your original code snippet, the following should be true:Note the 'Parent' is in quotes, you had it unquoted. Passing the class name as a string.
例子:
if (method_exists('父级', 'myFunction')
如果您想检查父构造函数,则它在 PHP 5.3.5 中不起作用。
但这对我有用:
只有当它存在于父类中时,它才会调用父构造函数
The example:
if (method_exists('Parent', 'myFunction')
does not work in PHP 5.3.5 if you like to check for a parent constructor.
But this worked for me:
It calls the Parent Constructor only if the it exists in the parent class
在这种情况下,子类必须扩展父类
Update我相信这与 method_exists 具有相同的效果。刚刚从 Wrikken 的帖子更新
Class child must extend the parent in that case
UpdateThis would have the same effect as method_exists I believe.Just updated from Wrikken's post
您应该使用 PHP 的 Reflection API:
如果您想了解 该方法所在的(父)类:
You should use PHP's Reflection API:
And if you want to know in which (parent) class the method lives:
如果您想具体知道它是否存在于父类中,而不是仅存在于您自己的类中:
If you want to know specifically if it exists in the parent, and not only in your own class: