Question

Having a little trouble with this static 'inheritance' in php 5.3 I need to test if a static function exists in static class but I need to test it from inside a parent static class.

I know in php 5.3 I can use the 'static' keyword to sort of simulate 'this' keyword. I just can't find a way to test if function exists.

Here is an example:

// parent class
class A{

// class B will be extending it and may or may not have 
// static function name 'func'
// i need to test for it

    public static function parse(array $a){
        if(function_exists(array(static, 'func'){
            static::func($a);
        }
    }
}

class B extends A {
    public static function func( array $a ){
        // does something
    }
}

So now I need to execute B::parse(); the idea is that if subclass has a function, it will be used, otherwise it will not be used.

I tried:

function_exists(static::func){}
isset(static::func){}

These 2 do not work.

Any ideas how to do this? By the way, I know about the possibility to passing a lambda function as a workaround, this is not an option in my situation.

I have a feeling there is a very simple solution that I just can't think of right now.

Now I need to call

Was it helpful?

Solution

You can't use function_exists for classes and objects (methods), only functions. You have to use method_exists or is_callable. isset only works with variables. Also, static does not simulate $this, they are two completely different things.

That being said, in that specific case, you have to use is_callable with a quoted static keyword:

if (is_callable(array('static', 'func'))) {
    static::func();
}

or...

if (is_callable('static::func')) {
    static::func();
}

OTHER TIPS

Try

public static function parse(array $a){
    if(function_exists(array(get_called_class(), 'func') {
/*...*/

See http://php.net/get_called_class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top