Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a method exists in an extended class but not parent class

Tags:

php

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)?

like image 715
xiankai Avatar asked Dec 16 '13 05:12

xiankai


3 Answers

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
like image 154
Elantcev Mikhail Avatar answered Oct 17 '22 01:10

Elantcev Mikhail


you can use reflection

$refl = new ReflectionClass($class_name); 

if($refl->hasMethod($method_name)){
       //do your stuff here 
}

for more information ReflectionClass

like image 40
user2907171 Avatar answered Oct 17 '22 01:10

user2907171


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
}
like image 37
sleepless Avatar answered Oct 17 '22 00:10

sleepless