- ReflectionClass::hasMethod
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 6 notes
- PHP method_exists
- Introduction to the PHP method_exists function
- PHP method_exists function examples
- 1) Using the PHP method_exists() function to check if a class has a method
- 2) Using the PHP method_exists function to check if an object has a method
- 3) Using the method_exists function to check if an object has a static method
- PHP method_exists function in MVC frameworks
- Summary
- Check if class has method in PHP
- Check if class has method in PHP
ReflectionClass::hasMethod
Checks whether a specific method is defined in a class.
Parameters
Name of the method being checked for.
Return Values
true if it has the method, otherwise false
Examples
Example #1 ReflectionClass::hasMethod() example
Class C public function publicFoo () return true ;
>
?php
protected function protectedFoo () return true ;
>
private function privateFoo () return true ;
>
static function staticFoo () return true ;
>
>
$rc = new ReflectionClass ( «C» );
var_dump ( $rc -> hasMethod ( ‘publicFoo’ ));
var_dump ( $rc -> hasMethod ( ‘protectedFoo’ ));
var_dump ( $rc -> hasMethod ( ‘privateFoo’ ));
var_dump ( $rc -> hasMethod ( ‘staticFoo’ ));
// C should not have method bar
var_dump ( $rc -> hasMethod ( ‘bar’ ));
// Method names are case insensitive
var_dump ( $rc -> hasMethod ( ‘PUBLICfOO’ ));
?>
The above example will output:
bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
See Also
User Contributed Notes 6 notes
Parent methods (regardless of visibility) are also available to a ReflectionObject. E.g.,
class ParentObject <
public function parentPublic ( ) <
>
private function parentPrivate ( ) <
>
>
class ChildObject extends ParentObject <
>
$Instance = new ChildObject ();
$Reflector = new ReflectionObject ( $Instance );
var_dump ( $Reflector -> hasMethod ( ‘parentPublic’ )); // true
var_dump ( $Reflector -> hasMethod ( ‘parentPrivate’ )); // true
?>
Trait methods can be seen by both actual and alias names
trait Sauce
public function getSpicy ()
return ‘Cayenne’ ;
>
>
class Sandwich
use Sauce Sauce :: getSpicy as getSweet ;
>
>
$class = new \ ReflectionClass ( ‘Sandwich’ );
var_dump ( $class -> hasMethod ( ‘getSweet’ ));
var_dump ( $class -> hasMethod ( ‘getSpicy’ ));
?>
bool(true)
bool(true)
Annotated methods that are implemented using PHP magic methods are not recognized by «hasMethod».
/**
* @method void annotatedMethod()
*/
class SomeClass
public function __call ( $name , $arguments )
echo «this is magic method: $name .\n» ;
>
public function codedMethod ()
echo «this is coded method.\n» ;
>
>
$obj = new \ SomeClass ();
$obj -> codedMethod ();
$obj -> annotatedMethod ();
$ref = new ReflectionClass (\ SomeClass ::class);
echo «SomeClass has ‘codedMethod’: » . json_encode ( $ref -> hasMethod ( ‘codedMethod’ )) . «.\n» ;
echo «SomeClass has ‘annotatedMethod’: » . json_encode ( $ref -> hasMethod ( ‘annotatedMethod’ )) . «.\n» ;
?>
Output:
this is coded method.
this is magic method: annotatedMethod.
SomeClass has ‘codedMethod’: true.
SomeClass has ‘annotatedMethod’: false.
It might be interesting to know that this is the only method to determine if a trait has a specific method:
trait a function __wakeup()<>
>
var_dump((new ReflectionClass(‘a’))->hasMethod(‘__wakeup’)); // true
var_dump((new ReflectionClass(‘b’))->hasMethod(‘__wakeup’)); // false
var_dump((new ReflectionClass(‘c’))->hasMethod(‘__wakeup’)); // true
A way to check if you can call an method over a class:
function is_public_method (
/* string */ $className ,
/* string */ $method
) $classInstance = new ReflectionClass ( $className );
if ( $classInstance -> hasMethod ( $method )) return false ;
>
$methodInstance = $instance -> getMethod ( $method );
return $methodInstance -> isPublic ();
>
?>
- ReflectionClass
- __construct
- getAttributes
- getConstant
- getConstants
- getConstructor
- getDefaultProperties
- getDocComment
- getEndLine
- getExtension
- getExtensionName
- getFileName
- getInterfaceNames
- getInterfaces
- getMethod
- getMethods
- getModifiers
- getName
- getNamespaceName
- getParentClass
- getProperties
- getProperty
- getReflectionConstant
- getReflectionConstants
- getShortName
- getStartLine
- getStaticProperties
- getStaticPropertyValue
- getTraitAliases
- getTraitNames
- getTraits
- hasConstant
- hasMethod
- hasProperty
- implementsInterface
- inNamespace
- isAbstract
- isAnonymous
- isCloneable
- isEnum
- isFinal
- isInstance
- isInstantiable
- isInterface
- isInternal
- isIterable
- isIterateable
- isReadOnly
- isSubclassOf
- isTrait
- isUserDefined
- newInstance
- newInstanceArgs
- newInstanceWithoutConstructor
- setStaticPropertyValue
- __toString
- export
PHP method_exists
Summary: in this tutorial, you’ll learn how to use the PHP method_exists() function to check if a class or an object of a class has a specified method.
Introduction to the PHP method_exists function
The method_exists() function returns true if an object or a class has a specified method. Otherwise, it returns false .
The syntax of the method_exists() function is as follows:
method_exists(object|string $object_or_class, string $method): bool
Code language: PHP (php)The method_exists() has two parameters:
- $object_or_class is an object or a class in which you want to check if a method exists.
- $method is a string that represents the method to check.
PHP method_exists function examples
Let’s take some examples of using the method_exists() function.
1) Using the PHP method_exists() function to check if a class has a method
The following example uses the method_exists() function to check if a method exists in the BankAccount class:
class BankAccount < public function transferTo(BankAccount $other, float $amount) < // more code > > $exists = method_exists(BankAccount::class, 'transferTo'); var_dump($exists); // bool(true) $exists = method_exists(BankAccount::class, 'deposit'); var_dump($exists); // bool(false)
Code language: PHP (php)In this example, the following statement returns true because the transferTo method exists in the BankAccount class:
method_exists(BankAccount::class, 'transferTo');
Code language: PHP (php)However, the following statement returns false because the deposit method doesn’t exist in the BankAccount class:
method_exists(BankAccount::class, 'deposit');
Code language: PHP (php)2) Using the PHP method_exists function to check if an object has a method
The following example creates a new object of the BankAccount and uses the method_exists() function to check the object has a specified method:
class BankAccount < public function transferTo(BankAccount $other, float $amount) < // more code > > $account = new BankAccount(); $exists = method_exists($account, 'transferTo'); var_dump($exists); // bool(true) $exists = method_exists($account, 'deposit'); var_dump($exists); // bool(false)
Code language: PHP (php)The $account object has the transferTo method, therefore, the following statement returns true :
method_exists($account, 'transferTo');
Code language: PHP (php)On the other hand, the $account object doesn’t have the deposit method. Therefore, the following statement returns false :
method_exists($account, 'deposit');
Code language: PHP (php)3) Using the method_exists function to check if an object has a static method
The method_exists() also returns true if a class has a static method. For example:
class BankAccount < public function transferTo(BankAccount $other, float $amount) < // more code > public static function compare(BankAccount $other): bool < // implementation // . return false; > > $exists = method_exists(BankAccount::class, 'compare'); var_dump($exists); // bool(true) $account = new BankAccount(); $exists = method_exists($account, 'compare'); var_dump($exists); // bool(true)
Code language: PHP (php)The BankAccount has the compare static method, so the following statement returns true :
method_exists(BankAccount::class, 'compare');
Code language: PHP (php)The $account is an instance of the BankAccount class that has the compare static method, the following expression also returns true :
$exists = method_exists($account, 'compare');
Code language: PHP (php)PHP method_exists function in MVC frameworks
The method_exists() method is often used in Model-View-Controller (MVC) frameworks to check if a controller class has a certain method before calling it.
For example, suppose that you have the following request URI:
/posts/edit/1
Code language: PHP (php)This URI has three parts: posts, edit, and 1.
- The posts maps to the PostsController class.
- The edit maps the edit method of the class.
- The number 1 is the post id to edit.
The PostsController class will look like the following:
class PostsController < public function edit(int $id) < // show the edit post form > >
Code language: PHP (php)And you use the method_exists() function to check whether the edit method exists in the $controller object like this:
// . if(method_exists($controller, $action)) < $controller->$action($id); >
Code language: PHP (php)Summary
Check if class has method in PHP
In PHP, you can easily check if a class has a specific method using the `method_exists()` function. This function returns a boolean value indicating whether the method exists or not.
Here is an example of how to use `method_exists()`:
class MyClass < public function myMethod() < // do something >> $object = new MyClass(); if (method_exists($object, 'myMethod')) < echo "Method exists!"; >else
In this example, we create a class called `MyClass` with a method called `myMethod`. We then create an instance of the class and use `method_exists()` to check if the method exists. Since the method does exist, the code will output “Method exists!”.
It’s important to note that `method_exists()` only checks if a method exists within the class itself. It does not check for methods inherited from parent classes. If you need to check for inherited methods, you can use the `is_callable()` function instead.
Here is an example of how to use `is_callable()` to check for inherited methods:
class ParentClass < protected function myMethod() < // do something >> class ChildClass extends ParentClass < >$object = new ChildClass(); if (is_callable(array($object, 'myMethod'))) < echo "Method exists!"; >else
In this example, we create a parent class called `ParentClass` with a protected method called `myMethod`. We then create a child class called `ChildClass` that extends `ParentClass`. We create an instance of `ChildClass` and use `is_callable()` to check if the `myMethod` method is callable. Since the method is inherited from the parent class, the code will output “Method exists!”.
I hope this guide was helpful in understanding how to check if a class has a method in PHP.
Check if class has method in PHP
In PHP, you can easily check if a class has a specific method using the `method_exists()` function. This function returns a boolean value indicating whether the method exists or not.
Here is an example of how to use `method_exists()`:
class MyClass < public function myMethod() < // do something >> $object = new MyClass(); if (method_exists($object, 'myMethod')) < echo "Method exists!"; >else
In this example, we create a class called `MyClass` with a method called `myMethod`. We then create an instance of the class and use `method_exists()` to check if the method exists. Since the method does exist, the code will output “Method exists!”.
It’s important to note that `method_exists()` only checks if a method exists within the class itself. It does not check for methods inherited from parent classes. If you need to check for inherited methods, you can use the `is_callable()` function instead.
Here is an example of how to use `is_callable()` to check for inherited methods:
class ParentClass < protected function myMethod() < // do something >> class ChildClass extends ParentClass < >$object = new ChildClass(); if (is_callable(array($object, 'myMethod'))) < echo "Method exists!"; >else
In this example, we create a parent class called `ParentClass` with a protected method called `myMethod`. We then create a child class called `ChildClass` that extends `ParentClass`. We create an instance of `ChildClass` and use `is_callable()` to check if the `myMethod` method is callable. Since the method is inherited from the parent class, the code will output “Method exists!”.
I hope this guide was helpful in understanding how to check if a class has a method in PHP.