Classes/Object 函数
在线手册:中文 英文
PHP手册

method_exists

(PHP 4, PHP 5)

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)

参见 function_exists()is_callable()

参数

object

An object instance or a class name

method_name

The method name

返回值

Returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

注释

Note:

如果此类不是已知类, 使用此函数会使用任何已注册的 autoloader

范例

Example #2 method_exists() example

<?php
$directory 
= new Directory('.');
var_dump(method_exists($directory,'read'));
?>

以上例程会输出:

bool(true)

Example #3 Static method_exists() example

<?php
var_dump
(method_exists('Directory','read'));
?>

以上例程会输出:

bool(true)

参见


Classes/Object 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 检查类的方法是否存在

用户评论:

Niels (11-May-2011 08:45)

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')));
?>

mail at bartrail dot de (25-Apr-2011 06:06)

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', $method, get_class($this)));
        }
    }

}
?>

phoenix at todofixthis dot com (21-Dec-2010 05:13)

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
?>

buggedcom (19-Aug-2010 07:02)

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

uramihsayibok, gmail, com (07-Aug-2010 06:09)

It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump
(method_exists("Iterator", "current"));
// bool(true)

?>

Anonymous (08-May-2010 01:20)

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

admin ( at ) djokodonev dot com (17-Oct-2009 12:30)

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..
?>

florin from syneto net (07-Oct-2009 03:34)

This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function
FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>

jp at function dot fi (30-Apr-2006 10:29)

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)

?>

seufert at gmail dot com (27-Apr-2006 02:27)

Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function
test() {return "A";}
}
if(
method_exists('a','test'))
    print
call_user_func(array('a','test'));
else
    print
"Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.

spam at majiclab dot com (31-Jan-2006 04:33)

Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.

daniel at softel dot jp (10-Jan-2006 03:34)

Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.

jpgiot at nospam ifrance.com (06-May-2004 03:42)

a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo
'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo
'ok';
?>

Thomas@ThBeckmann (31-Jan-2003 09:47)

Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))

benjamin_ansbach at web dot de (27-Dec-2002 08:49)

if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function
a() {
       
        if(
method_exists($this, 'test'))
            echo
'a::test() exists!';
        else
            echo
'a::test() doesn\'t exists';

    }

   
    function
test() {
       
        return
true;
   
    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone

j dot metzger at steptown dot com (16-Jan-2002 11:42)

call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.