42

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.

2
  • Why isn't the test1() method sufficient?
    – gapple
    Jul 21, 2009 at 0:19
  • Because I want to put this into a class that will be extended by multiple classes. I could use a magic constant to achieve this, but there should be an easier way. Jul 21, 2009 at 0:31

3 Answers 3

62

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()"
2
  • I was looking for a way to check if a static method exists on the parent class, and this answer led me to discover that get_parent_class() works the same way when called without any params. Thanks!
    – mopo922
    May 4, 2016 at 5:10
  • 2
    Just a note static::class does the same as get_called_class() and self::class does the same as get_class() but they are only available since PHP 5.5
    – Tofandel
    Jul 17, 2018 at 9:37
14

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"; }
6
  • 1
    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
    Jul 21, 2009 at 0:21
  • 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. Jul 21, 2009 at 0:27
  • You mean from the comments that I 'just' put on the main question? Jul 21, 2009 at 0:35
  • 1
    If extensibility is your goal, it should be noted that __CLASS__, __TRAIT__, __FILE__, etc explicitly returns the name of the class/trait/file where the constant is used, whereas if you want to account for child objects, you will want get_class($this) for instantiated objects, or get_called_class() for static classes/methods to track inheritance. Then you can drop one function in a trait or base class and use it everywhere, thereby preventing code duplication issues, and use instanceof [trait, parent class, or interface] or method_exists() for validation without duplicate code.
    – mopsyd
    Sep 20, 2017 at 18:58
  • 1
    Also in PHP 7+, the static::PROPERTY construct was added to simplify late static binding. Eg: return self::PROPERTY -> always returns from current class scope, return static::PROPERTY -> returns highest level declaration, honoring child class overrides of class constants, static functions, etc.
    – mopsyd
    Sep 20, 2017 at 19:05
-1

for all situations… the best usage would be…

if method_exist(…) && is_callable(…)

For testing example:

class Foo {
  public function PublicMethod() {}
  private function PrivateMethod() {}
  public static function PublicStaticMethod() {}
  private static function PrivateStaticMethod() {}
}

$foo = new Foo();

$callbacks = array(
  array($foo, 'PublicMethod'),
  array($foo, 'PrivateMethod'),
  array($foo, 'PublicStaticMethod'),
  array($foo, 'PrivateStaticMethod'),
  array('Foo', 'PublicMethod'),
  array('Foo', 'PrivateMethod'),
  array('Foo', 'PublicStaticMethod'),
  array('Foo', 'PrivateStaticMethod'),
);

foreach ($callbacks as $callback) {
  var_dump($callback);
  var_dump(method_exists($callback[0], $callback[1])); // 0: object / class name, 1: method name
  var_dump(is_callable($callback));
  echo str_repeat('-', 40), "n";
}

Source here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.