php 类方法是否存在,PHP函数method_exists检查类是否存在和与is_callable()的区别

PHP method_exists 检查类的方法是否存在

method_exists

method_exists — 检查类的方法是否存在

说明

bool method_exists ( object $object , string $method_name )

如果 method_name 所指的方法在 object 所指的对象类中已定义,则返回 TRUE,否则返回 FALSE。

Example #1 method_exists() 例子

<?php $directory= newDirectory('.');var_dump(method_exists($directory,'read'));?>以上例程会输出:bool(true)

PHP method_exists note #1

Just to mention it: both method_exists() and is_callable() return true for inherited methods:<?phpclassParentClass {   functiondoParent() { }}classChildClassextendsParentClass{ }$p= newParentClass();$c= newChildClass();// all return truevar_dump(method_exists($p,'doParent'));var_dump(method_exists($c,'doParent'));var_dump(is_callable(array($p,'doParent')));var_dump(is_callable(array($c,'doParent')));?>

PHP method_exists note #2

Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application: <?phpclassSomething {/**      * Call a method dynamically      *      * @param string $method      * @param array $args      * @return mixed      */public function__call($method,$args)     {         if(method_exists($this,$method)) {           returncall_user_func_array(array($this,$method),$args);         }else{           throw newException(sprintf('The required method "%s" does not exist for %s',$method,get_class($this)));         }     } }?>

PHP method_exists note #3

As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does: <?phpclassTest {   public functionexplicit(  ) {// ...}      public function__call($meth,$args) {// ...} }$Tester= newTest();var_export(method_exists($Tester,'anything'));// falsevar_export(is_callable(array($Tester,'anything')));// true?>

PHP method_exists note #4

Be warned that the class must exist before calling method exists from an eval statement otherwise you will get a Signal Bus error.

PHP method_exists note #5

It wasn't spelled out but could be inferred: method_exists() also works on interfaces.<?phpvar_dump (method_exists("Iterator","current"));// bool(true)?>

PHP method_exists note #6

If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__<?phpclassA {__construct($method){      returnmethod_exists(__CLASS__,$method);  }  private functionfoo(){    }}$test= newA('foo');//should return true?>You might also use the method describe below with <?php in_array()?>trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)

PHP method_exists note #7

Hi, Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both.. here it goes: <?php // Example classclassmyClass{     private$private1;         static$static1;         public$public1;                 public functionpubl() {         }         private functionpriv() {         }         private static functionprivstatic() {     }         public static functionpublstatic() {         }         static functionmytest() {         } }// The function uses the reflection class that is built into PHP!!! // The purpose is to determine the type of a certain method that exifunctionis_class_method($type="public",$method,$class) {// $type = mb_strtolower($type);$refl= newReflectionMethod($class,$method);     switch($type) {         case"static":         return$refl->isStatic();         break;         case"public":         return$refl->isPublic();         break;         case"private":         return$refl->isPrivate();         break;     } }var_dump(is_class_method("static","privstatic","myClass"));// true - the method is  private and also static..var_dump(is_class_method("private","privstatic","myClass"));// true - the method is  private and also static..var_dump(is_class_method("private","publstatic","myClass"));// False the methos is public and also static not private  // you get the idea.. I hope this helps someone..?>

PHP method_exists note #8

This function is case-insensitive (as is PHP) and here is the proof:<?phpclassA {    public functionFUNC() { echo'*****'; }}$a= newA();$a->func();// *****var_dump(method_exists($a,'func'));// bool(true)?>

PHP method_exists note #9

As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.<?phpclassFoo1 {  public functionbar() {    echo"I'm private Foo1::bar()";  }}classFoo2{  private functionbar() {    echo"I'm public Foo2::bar()";  }}$f1=newFoo1;$f2=newFoo2;if(is_callable(array($f1,"bar"))) {    echo"Foo1::bar() is callable";} else {    echo"Foo1::bar() isn't callable";}if(is_callable(array($f2,"bar"))) {    echo"Foo2::bar() is callable";} else {    echo"Foo2::bar() isn't callable";}if(in_array("bar",get_class_methods($f1))) {    echo"Foo1::bar() is callable";} else {    echo"Foo1::bar() isn't callable";}if(in_array("bar",get_class_methods($f2))) {    echo"Foo2::bar() is callable";} else {    echo"Foo2::bar() isn't callable";}?>outputFoo1::bar() is callable (correct)Foo2::bar() is callable (incorrect)Foo1::bar() is callable (correct)Foo2::bar() isn't callable (correct)?>

在编程中,我们有的时候需要判断某个类中是否包含某个方法,除了使用反射机制,PHP还提供了method_exists()和is_callable()方法进行判断。那么两则区别是什么呢?

已知类文件如下:class Student{

private $alias=null;    private $name='';    public function __construct($name){

$this->name=$name;

}    private function setAlias($alias){

$this->alias=$alias;

}    public function getName(){

return $this->name;

}

}12345678910111213

当方法是private,protected类型的,method_exists会报错,is_callable会返回false。

实例

下面是判断某一对象中是否存在方法getName

通过method_exists实现$xiaoming=new Student('xiaoming');if (method_exists($xiaoming, 'getName')) {

echo 'exist';

}else{    echo 'not exist';

}exit();1234567

输出exist

通过is_callable实现$xiaoming=new Student('xiaoming');if (is_callable(array($xiaoming, 'getName'))) {

echo 'exist';

}else{    echo 'not exist';

}exit();1234567

输出exist

下面是判断某一对象中是否存在方法setAlias 当使用method_exists的时候报错如下

8235ff0e16198dab76efcbe3d8af9aeb.png

当使用is_callable的时候,输出not exist

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值