tags:

views:

433

answers:

3

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.

A: 

Update:

Ahh, apologies. I was temporarily blind :) You'll want to use the magic constant __CLASS__

e.g.

if (method_exists(__CLASS__, "test3")) { echo "Hi"; }
hobodave
this answer seems to be the same as the question example's test1() method using method_exists() with the class name passed as a string
GApple
The idea is that I don't need a class name, and I can therefore put the method in any class, and it should work, whether the class has been assigned or not.
Chacha102
You mean from the comments that I 'just' put on the main question?
Chacha102
I don't understand the question. I see you updated your comment in the OP with: "I could use a magic constant to achieve this, but there should be an easier way." I did not see this before I updated my answer.What is not easy enough about the given method?
hobodave
A: 
$self =& self;

create a link to left and pass it as parameter.

Ilya Biryukov
This would not work for a static class, that is not instantiated
GApple
+3  A: 

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 called (eg., the parent class):

class myClass{
    function test()
    {
        if(method_exists(get_class(), "test"))
        {
                echo get_class().'::test()';
        }
    }
}

class subClass extends myClass{}

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

The __CLASS__ magic constant may do the same as well [link].

class myClass{
    function test()
    {
        if(method_exists(__CLASS__, "test"))
        {
                echo __CLASS__.'::test()';
        }
    }
}

get_called_class() should be your solution

class myClass{
    function test()
    {
        if(method_exists(get_called_class(), "test"))
        {
                echo get_called_class().'::test()';
        }
    }
}

class subClass extends myClass{}

subClass::test() // should print "subClass::test()"
GApple
Thank You! That was exactly what I was looking for.
Chacha102