method_exists

(PHP 4, PHP 5)

method_exists — Проверяет существует ли метод в данном классе

Описание

bool method_exists ( object $object , string $method_name )

Функция возвращает TRUE если метод method_name был объявлен для object . В противном случае функция возвращает FALSE.

Пример #1 Пример использования method_exists()

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

выведет:

bool(true)

Коментарии

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.
2002-01-16 05:42:21
http://php5.kiev.ua/manual/ru/function.method-exists.html
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 {

    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
2002-12-27 14:49:44
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
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>))
2003-01-31 15:47:43
http://php5.kiev.ua/manual/ru/function.method-exists.html
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';
?>
2004-05-06 10:42:57
http://php5.kiev.ua/manual/ru/function.method-exists.html
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
2006-01-09 21:34:18
http://php5.kiev.ua/manual/ru/function.method-exists.html
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.
2006-01-31 10:33:59
http://php5.kiev.ua/manual/ru/function.method-exists.html
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 {
    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.
2006-04-26 21:27:47
http://php5.kiev.ua/manual/ru/function.method-exists.html
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)

?>
2006-04-30 05:29:48
http://php5.kiev.ua/manual/ru/function.method-exists.html
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)
?>
2009-10-07 10:34:52
http://php5.kiev.ua/manual/ru/function.method-exists.html
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..
?>
2009-10-16 19:30:51
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
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 ;)
2010-05-08 08:20:43
http://php5.kiev.ua/manual/ru/function.method-exists.html
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

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

?>
2010-08-07 01:09:16
http://php5.kiev.ua/manual/ru/function.method-exists.html
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
?>
2010-12-21 11:13:51
http://php5.kiev.ua/manual/ru/function.method-exists.html
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)));
        }
    }

}
?>
2011-04-25 13:06:16
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
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')));
?>
2011-05-11 15:45:50
http://php5.kiev.ua/manual/ru/function.method-exists.html
Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

<?php
namespace test;
class 
foo {
 public function 
lookup() {
 
// will return false
 
return method_exists('bar''nonsense_method');
 }
}

class 
bar {
 public function 
nonsense_method() {
 
// will return true
 
return method_exists('test\foo''lookup');
 }
}
?>
2013-02-15 07:32:55
http://php5.kiev.ua/manual/ru/function.method-exists.html
I was wondering if caching the the methods in an array would have a faster lookup. So I ran a very simple benchmark using xdebug_time_index() with 10000 iterations on each statement.

using PHP 5.3.13 btw

<?php 
// using an actual instance of an object shows 0.10398316383362 secs
method_exist($object$method);
?>

<?php 
// using a string shows 0.12779307365417 secs
method_exist('ClassName'$method);
?>

<?php 
$array 
= array(/*method names with numeric index*/);
// shows 0.10288906097412 secs
in_array($method$array);
?>

<?php 
$assoc 
= array( /*method name as key and value*/ );
// shows 0.017536878585815 secs
isset( $assoc[$method] );
?>

From the looks of the results, there is very little difference in method_exist and in_array. Isset seems to the fastest and using a string as the first parameter is the slowest.

Please note that the test was done on multiple methods, not just one, the code presented above is to show the results, not the actual test code that ran. Also, this was tested just out of curiosity and I didn't set up a specific environment or used any profiling tools, and it was not meant to be an official benchmark in anyway.
2014-10-10 07:31:45
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
A couple of the older comments (specifically "jp at function dot fi" and "spam at majiclab dot com") state that is_callable() does not respect a methods visibility when checked outside of that class. ie. That private/protected methods are seen as callable when tested publicly. However, this was a bug (#29210) in early versions of PHP 5 and was fixed (according to the changelog) in PHP 5.0.5 (and/or PHP 5.1.0).

Bug #29210 - Function: is_callable - no support for private and protected classes
http://bugs.php.net/29210

Changelog - Fixed bug #29210 (Function: is_callable - no support for private and protected classes). (Dmitry)
http://php.net/ChangeLog-5.php#5.1.0
2015-04-05 01:38:45
http://php5.kiev.ua/manual/ru/function.method-exists.html
The function does not care about class existance, so you can use it to check an existance of a method even when class was not declared e.g.
<?php
if( method_exists('THIS_WAS_NOT_DECLARED''some_method') ) 
   echo 
"it does exist!"
else 
   echo 
"nope, it is not there...";
?>
...raises no errors/warnings... outputs "nope, it is not there..." if class does not exist at all or if it does but the method doesn't.
2016-06-01 20:15:09
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
Undocumented change since 7.4.0 is released:

<?php
class Foo 

    private function 
privateMethodTest() 
    {
       
    } 


class 
Bar extends Foo 
{
   


var_dump(method_exists(Bar::class, 'privateMethodTest'));
// PHP 7.4: bool(false)
// PHP 7.3: bool(true)

var_dump(is_callable(Bar::class, 'privateMethodTest'));
// PHP 7.3: bool(true)
// PHP 7.4: bool(true)
2019-12-02 22:39:14
http://php5.kiev.ua/manual/ru/function.method-exists.html
Автор:
if u want to use  "method_exit" function in diffrent file after including this class , then u can't use it directly by "method_exit"

so for this u have to use call_user_func_array to a base function which is available in class already.

then call function in the following way=>

function check($fun) {
       
        if(method_exists($this, $fun))
            {return true;} 
        else
            {return false;}
           

    }
2021-12-16 06:16:05
http://php5.kiev.ua/manual/ru/function.method-exists.html

    Поддержать сайт на родительском проекте КГБ