找出静态类中是否存在方法 [英] Find out if a method exists in a static class
问题描述
我要检查的是我正在创建的库中是否存在函数,该函数是静态的.我已经看过function和method_exists,但是还没有找到一种允许我在相对上下文中调用它们的方法.这是一个更好的示例:
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();
如果函数存在,我需要能够使test 3 echo Hi,而无需将其移出静态上下文.假设用于访问该类的关键字应该是"self",因为$ this是用于分配的类.
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.
推荐答案
static::class
自PHP 5.5起可用,并将返回"
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()
相同,并在PHP 5.3中引入
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()"
get_class()
函数如果在类中调用php 5.0.0,则不需要任何参数,它将返回声明该函数的类的名称(例如,父类):
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()"
__CLASS__
魔术常数的作用相同[链接].
class myClass {
public static function test()
{
echo __CLASS__.'::test()';
}
}
class subClass extends myClass {}
subClass::test() // prints "myClass::test()"
这篇关于找出静态类中是否存在方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!