您现在的位置: 365建站网 > 365文章 > PHP函数method_exists检查类是否存在和与is_callable()的区别

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

文章来源:365jz.com     点击数:1407    更新时间:2018-08-26 08:45   参与评论

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 
= new Directory('.');
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:

<?php
class ParentClass {

   function 
doParent() { }
}

class 
ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_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: 

<?php 
class Something 


    
/** 
     * Call a method dynamically 
     * 
     * @param string $method 
     * @param array $args 
     * @return mixed 
     */ 
    
public function __call($method$args
    { 
        if(
method_exists($this$method)) { 
          return 
call_user_func_array(array($this$method), $args); 
        }else{ 
          throw new 
Exception(sprintf('The required method "%s" does not exist for %s'$methodget_class($this))); 
        } 
    } 


?>

PHP method_exists note #3

As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does: 

<?php 
class Test 
  public function 
explicit(  ) { 
      
// ... 
  

   
  public function 
__call$meth$args ) { 
      
// ... 
  



$Tester = new Test(); 

var_export(method_exists($Tester'anything')); // false 
var_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.

<?php

var_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__

<?php

class A{
  
__construct($method){
      return 
method_exists(__CLASS__,$method);
  }

  private function 
foo(){
  
  }
}

$test = new A('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 class 
class myClass 

    private 
$private1
    
    static 
$static1
    
    public 
$public1
        
    
    public function 
publ() { 
    
    } 
    
    private function 
priv() { 
    
    } 
    
    private static function 
privstatic() { 

    } 
    
    public static function 
publstatic() { 
    
    } 
    
    static function 
mytest() { 
    
    } 


// The function uses the reflection class that is built into PHP!!! 
// The purpose is to determine the type of a certain method that exi 
function is_class_method($type="public"$method$class) { 
   
// $type = mb_strtolower($type); 
    
$refl = new ReflectionMethod($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:
<?php
class {
    public function 
FUNC() { echo '*****'; }
}

$a = new A();
$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.

<?php
class Foo1 {
  public function 
bar() {
    echo 
"I'm private Foo1::bar()";
  }
}

class 
Foo2 {
  private function 
bar() {
    echo 
"I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

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

?>

output
Foo1::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的时候报错如下 
 20160810172253227.jpg

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


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (1407人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号