Reputation: 6197
I know theres a method_exists() but it says true even when that method is inherited.
class A
{
public function eix()
{
}
}
class B extends A
{
}
echo method_exists ('B', 'eix');
so its true, but B class doesnt have it. How to dodge this?
Upvotes: 0
Views: 197
Reputation: 18253
Since class B extends class A it inherent all of its methods and method_exists()
will always return true.
Question is why you would need to know whether the method is first created in class A or class B? I see no reason for why one would need this information.
And if this is a problem, you should probably reconsider your architectural design from the start.
But just as Mark Baker explains, one could probably find out at least if the method exist in parent class as well, doesn't necessarily mean it haven't been overridden in the child class.
if(method_exists(get_parent_class('B'), 'eix'))
{
//Exist in parent class and was not first created in this.
//But still is inherent to this.
}
else
{
//Doesn't exist in parent and must been created in this.
}
Upvotes: 0
Reputation: 212412
Use get_parent_class() to identify the parent, and then use method_exists() against that.
echo method_exists (get_parent_class('B'), 'eix');
Upvotes: 3
Reputation: 237865
You'll need to use reflection to achieve this. Look into the ReflectionMethod
class and you'll find the getDeclaringClass
method.
$classname = 'B';
$methodname = 'eix';
$method = new ReflectionMethod($classname, $methodname);
$declaringclass = $method->getDeclaringClass();
if ($classname == $declaringclass->name) {
// method was defined on the original class
}
That said, the key point is that class B
does have a method eix
, since it inherits all A
's methods that it doesn't redefine. I can't quite work out a circumstance where you'd need to know where the method was defined, but this technique allows you to do so if necessary.
Upvotes: 3