Find out if a method exists in a static class

后端 未结 3 1278
感动是毒
感动是毒 2020-12-28 12:54

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

3条回答
  •  半阙折子戏
    2020-12-28 13:18

    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

提交回复
热议问题