Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to check is a function exists in a library that I am creating, which is static. I've seen function and method_exists, but haven't found a way that allows me to call them in a relative context. Here is a better example:

class myClass{
    function test1()
    {
        if(method_exists("myClass", "test1"))
        {
            echo "Hi";
        }
    }
    function test2()
    {
        if(method_exists($this, "test2"))
        {
            echo "Hi";
        }
    }
    function test3()
    {
        if(method_exists(self, "test3"))
        {
            echo "Hi";
        }
    }
}
// Echos Hi
myClass::test1();
// Trys to use 'self' as a string instead of a constant
myClass::test3();
// Echos Hi
$obj = new myClass;
$obj->test2();

I need to be able to make test 3 echo Hi if the function exists, without needing to take it out of static context. Given the keyword for accessing the class should be 'self', as $this is for assigned classes.

question from:https://stackoverflow.com/questions/1156593/find-out-if-a-method-exists-in-a-static-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

static::class is available since PHP 5.5, and will return the "Late Static Binding" class name:

class myClass {
    public static function test()
    {
        echo static::class.'::test()';
    }
}

class subClass extends myClass {}

subClass::test() // should print "subClass::test()"

get_called_class() does the same, and was introduced in PHP 5.3

class myClass {
    public static function test()
    {
        echo get_called_class().'::test()';
    }
}

class subClass extends myClass {}

subClass::test() // should print "subClass::test()"

The get_class() function, which as of php 5.0.0 does not require any parameters if called within a class will return the name of the class in which the function was declared (e.g., the parent class):

class myClass {
    public static function test()
    {
        echo get_class().'::test()';
    }
}

class subClass extends myClass {}

subClass::test() // prints "myClass::test()"

The __CLASS__ magic constant does the same [link].

class myClass {
    public static function test()
    {
        echo __CLASS__.'::test()';
    }
}

class subClass extends myClass {}

subClass::test() // prints "myClass::test()"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...