tags:

views:

30

answers:

2

How would I go about ensuring that the overridden parent method exists before I call it?
I've tried this:

public function func() {
    if (function_exists('parent::func')) {
        return parent::func();
    }
}

However the function_exists never evaluates to true.

+2  A: 

I've not checked this, but is the correct function method_exists?:

http://php.net/manual/en/function.method-exists.php

Mike
method_exists doesn't work with parent, thanks though. For some reason I remember getting function_exists to work before, but it isn't now...
Nate Wagar
In that case, I'm not sure what you are trying to do. Perhaps you could combine it with get_parent class - something like this:method_exists(get_parent_class($this), 'func')I may be barking up the wrong tree though.
Mike
Ah, that actually works... once. It needs to loop to go any higher then the first parent.
Nate Wagar
`get_parent_class` will return false once it hits the last ancestor. A simple while loop will do the trick. It's still an ugly hack, of course.
Charles
Mike's answer in the comments is what I ended up with.
Nate Wagar
A: 
<?php
class super {
    public function m() {}
}

class sub extends super {
     public function m() {
        $rc = new ReflectionClass(__CLASS__);
        $namepc = $rc->getParentClass()->name;
        return method_exists($namepc, __FUNCTION__);
    }
}

$s = new sub;
var_dump($s->m());

gives bool(true). Not sure if this would work if the method was defined in a superclass of super, but it would be a matter of introducing a simple loop.

Artefacto
Mike's get_parent_class method accomplishes the same thing, without Reflection.
Nate Wagar