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
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()"
Ahh, apologies. I was temporarily blind :) You'll want to use the magic constant __CLASS__
e.g.
if (method_exists(__CLASS__, "test3")) { echo "Hi"; }
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