- Проверка существования метода в PHP
- Комментировать
- 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
- ReflectionClass::hasMethod
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 6 notes
- method_exists
- Parameters
- Return Values
- Examples
- Notes
- See Also
Проверка существования метода в PHP
Классы могут содержать динамические методы, наличие которых неочевидно внешнему разработчику. Кроме того, в процессе эксплуатации могут создаваться разнородные массивы объектов, которые могут содержать различные методы. Для подобных ситуаций необходимы инструменты проверки существования метода в классе. В качестве такого инструмента в PHP выступает функция «method_exists()».
Функция в качестве первого параметра принимает имя класса или объект, а в качестве второго имя метода и возвращает «true», если объект или класс имеет данный метод, и «false» в противном случае.
Продемонстрируем работу функции «method_exists()» и создадим класс «myExists», который будет содержать два метода, открытый и закрытый.
class myExists < public function method_public() < echo 'Открытый метод'; >private function method_private() < echo 'Закрытый метод'; >> $_Class_myExists = new myExists(); if(method_exists($_Class_myExists, 'method_public')) < echo 'Метод "method_public" существует'; > if(method_exists($_Class_myExists, 'method_private')) < echo 'Метод "method_private" существует'; > if(method_exists($_Class_myExists, 'method_protected')) < echo 'Метод "method_protected" существует'; > else < echo 'Метод "method_protected" не существует'; >
В примере при помощи функции «method_exists()» в объекте класса «myExists» проверяется наличие существующих методов «method_public()», «method_private()» и не существующего метода «method_protected()». Результат:
Метод "method_public" существует Метод "method_private" существует Метод "method_protected" не существует
Как видно из результата проверки, функция возвращает «true» для каждого из методов, независимо от его спецификатора доступа, «false» возвращается только в том случае, если объект не обладает ни закрытым, ни открытым методом с таким именем.
В качестве первого аргумента функции «method_exists()» используется объект класса «$_Class_myExists», однако для проверки метода вовсе не обязательно создавать объект, достаточно передать имя класса. Пример:
method_exists('myExists', 'method_public');
При работе с функцией «method_exists()» следует учитывать, что она не может определить наличие динамических методов, созданных при помощи специального метода «__call()», «__callStatic()».
Помимо функции «method_exists()» можно воспользоваться альтернативной функцией «is_callable()», которая в отличие от «method_exists()», кроме проверки метода класса позволяет проверить существование функции, не входящей в состав класса.
Работая со сторонним классом, разработчик зачастую не знает досконально всех методов данного класса. Для того чтобы получить их полный список, можно воспользоваться функцией «get_class_methods()». В качестве первого параметра функция принимает имя класса, а возвращает массив его открытых методов. Следует подчеркнуть, что закрытые методы этой функцией не возвращаются. Пример:
$_all_pulic_method = get_class_methods($_Class_myExists); echo '
'; print_r($_all_pulic_method); echo '';
Как можно видеть, закрытый метод «method_private()» не включён в результирующий массив. Динамические методы, которые эмулируются при помощи специального метода «__call()», «__callStatic()», также не попадают в список, получаемый при помощи функции «get_class_methods()».
Комментировать
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
ReflectionClass::hasMethod
Проверяет, определён ли в классе указанный метод или нет.
Список параметров
Возвращаемые значения
true , если метод определён, в противном случае false
Примеры
Пример #1 Пример использования ReflectionClass::hasMethod()
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 не имеет метода bar
var_dump ( $rc -> hasMethod ( ‘bar’ ));
// Имена методов регистронезависимые
var_dump ( $rc -> hasMethod ( ‘PUBLICfOO’ ));
?>
Результат выполнения данного примера:
bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
Смотрите также
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
method_exists
Проверяет, существует ли метод класса в данном object_or_class .
Parameters
Экземпляр объекта или имя класса
Return Values
Возвращает true , если метод, заданный method , был определен для данного object_or_class , иначе false .
Examples
Пример # 1 method_exists () Пример
$directory = new Directory('.'); var_dump(method_exists($directory,'read')); ?>
Выводится приведенный выше пример:
Пример # 2 Статические method_exists () Пример
var_dump(method_exists('Directory','read')); ?>
Выводится приведенный выше пример:
Notes
Note:
При использовании этой функции будут использоваться любые зарегистрированные автозагрузчики, если класс еще не известен.
See Also
- function_exists () — Возвращает истину, если данная функция была определена
- is_callable () — Убедитесь, что значение может быть вызвано как функция из текущей области.
- class_exists () — Проверяет, определен ли класс
PHP 8.2
(PHP 4 4.3.2, 5, 7, 8) memory_get_usage Возвращает объем выделенной PHP Возвращает объем памяти в байтах, который в настоящее время выделен вашему