找出静态类中是否存在方法

问题描述 投票:35回答:3

我想检查一个函数是否存在于我正在创建的库中,这是静态的。我见过函数和method_exists,但是没有找到允许我在相对上下文中调用它们的方法。这是一个更好的例子:

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();

如果函数存在,我需要能够使测试3回显Hi,而不需要将其从静态上下文中取出。鉴于访问该类的关键字应该是'self',因为$ this用于指定的类。

php static object
3个回答
56
投票

static::class自PHP 5.5起可用,并将返回“Late Static Binding”类名:

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中引入

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开始,如果在类中调用,则不需要任何参数,将返回声明函数的类的名称(例如,父类):

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

class subClass extends myClass {}

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

__CLASS__ magic constant做同样的[link]。

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

class subClass extends myClass {}

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

3
投票

Update:

啊,道歉。我暂时失明了:)你会想要使用魔法常数__CLASS__

EG

if (method_exists(__CLASS__, "test3")) { echo "Hi"; }

-1
投票

对于所有情况......最好的用法是......

if method_exist(…) && is_callable(…)

对于测试示例:

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";
}

来源here

© www.soinside.com 2019 - 2024. All rights reserved.