With method_exists
, it checks all methods, including the parent class.
Example:
class Toot {
function Good() {}
}
class Tootsie extends Toot {
function Bad() {}
}
function testMethodExists() {
// true
var_dump(method_exists('Toot', 'Good'));
// false
var_dump(method_exists('Toot', 'Bad'));
// true
var_dump(method_exists('Tootsie', 'Good'));
// true
var_dump(method_exists('Tootsie', 'Bad'));
}
How can I check that the method only exists on the current class and not parent class (ie. Tootsie
)?
Since v. 4.0.5 php has get_parent_class() method, that returns parent class. So you can handle it without relflection:
class A
{
function a() { /* ... */}
function b() { /* ... */}
}
class B extends A
{
function b() { /* ... */}
function c() { /* ... */}
}
function own_method($class_name, $method_name)
{
if (method_exists($class_name, $method_name))
{
$parent_class = get_parent_class($class_name);
if ($parent_class !== false) return !method_exists($parent_class, $method_name);
return true;
}
else return false;
}
var_dump(own_method('B', 'a')); // false
var_dump(own_method('B', 'b')); // false
var_dump(own_method('B', 'c')); // true
you can use reflection
$refl = new ReflectionClass($class_name);
if($refl->hasMethod($method_name)){
//do your stuff here
}
for more information ReflectionClass
If you need to know if the method exists in a given child regardless the existence in a parent class you can do it like this:
$reflectionClass = new ReflectionClass($class_name);
if ($reflectionClass->getMethod($method_name)->class == $class_name) {
// do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With