php check method exists

method_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

Список параметров

Экземпляр объекта или имя класса

Возвращаемые значения

Примеры

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

Результат выполнения данного примера:

Пример #2 Пример статического использования method_exists()

Результат выполнения данного примера:

Примечания

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс ещё не известен.

Смотрите также

User Contributed Notes 20 notes

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

Undocumented change since 7.4.0 is released:

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)

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

Just to mention it: both method_exists() and is_callable() return true for inherited methods:

class ChildClass extends ParentClass

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

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

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

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

?>

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

maybe this will help someone

Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

private function foo ()<

$test = new A ( ‘foo’ );
//should return true

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

a little difference :

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

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

// Example class
class myClass <

public function publ () <

private function priv () <

private static function privstatic () <

public static function publstatic () <

static function mytest () <

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.

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 ;

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn’t callable (correct)

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:

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

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

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.

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

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

Источник

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

Классы могут содержать динамические методы, наличие которых неочевидно внешнему разработчику. Кроме того, в процессе эксплуатации могут создаваться разнородные массивы объектов, которые могут содержать различные методы. Для подобных ситуаций необходимы инструменты проверки существования метода в классе. В качестве такого инструмента в PHP выступает функция «method_exists()».

Функция в качестве первого параметра принимает имя класса или объект, а в качестве второго имя метода и возвращает «true», если объект или класс имеет данный метод, и «false» в противном случае.

Продемонстрируем работу функции «method_exists()» и создадим класс «myExists», который будет содержать два метода, открытый и закрытый.

В примере при помощи функции «method_exists()» в объекте класса «myExists» проверяется наличие существующих методов «method_public()», «method_private()» и не существующего метода «method_protected()». Результат:

Как видно из результата проверки, функция возвращает «true» для каждого из методов, независимо от его спецификатора доступа, «false» возвращается только в том случае, если объект не обладает ни закрытым, ни открытым методом с таким именем.

В качестве первого аргумента функции «method_exists()» используется объект класса «$_Class_myExists», однако для проверки метода вовсе не обязательно создавать объект, достаточно передать имя класса. Пример:

При работе с функцией «method_exists()» следует учитывать, что она не может определить наличие динамических методов, созданных при помощи специального метода «__call()», «__callStatic()».

Помимо функции «method_exists()» можно воспользоваться альтернативной функцией «is_callable()», которая в отличие от «method_exists()», кроме проверки метода класса позволяет проверить существование функции, не входящей в состав класса.

Работая со сторонним классом, разработчик зачастую не знает досконально всех методов данного класса. Для того чтобы получить их полный список, можно воспользоваться функцией «get_class_methods()». В качестве первого параметра функция принимает имя класса, а возвращает массив его открытых методов. Следует подчеркнуть, что закрытые методы этой функцией не возвращаются. Пример:

Как можно видеть, закрытый метод «method_private()» не включён в результирующий массив. Динамические методы, которые эмулируются при помощи специального метода «__call()», «__callStatic()», также не попадают в список, получаемый при помощи функции «get_class_methods()».

Источник

method_exists

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

Описание

Список параметров

Экземпляр объекта или имя класса

Возвращаемые значения

Примечания

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.

Примеры

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

Результат выполнения данного примера:

Пример #2 Пример статического использования method_exists()

Результат выполнения данного примера:

Смотрите также

Коментарии

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

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

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

?>

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

maybe this will help someone

a little difference :

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

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

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

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.

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 ;

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn’t callable (correct)

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

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

// Example class
class myClass <

public function publ () <

private function priv () <

private static function privstatic () <

public static function publstatic () <

static function mytest () <

If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

private function foo ()<

$test = new A ( ‘foo’ );
//should return true

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

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

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:

Just to mention it: both method_exists() and is_callable() return true for inherited methods:

class ChildClass extends ParentClass

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

Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

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

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.

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

Undocumented change since 7.4.0 is released:

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)

Источник

method_exists() против is_callable()

Одну вещь, которую я часто вижу, когда просматриваю чужой код на php, это не правильное использование функции method_exists(), и это требует немного разъяснений.

Это типичный пример того, о чем я тут говорю

Да, но.

Этот код будет, вероятно, работать очень хорошо в течение всей своей жизни, но что если метод объекта будет не видим в текущем положении (к примеру метод private или protected)? PHP функция method_exists() делает следующее: она проверяет если класс или объект имеет метод исходя из того, что метод будет вызван внутри самого объекта. И вернет true если это так, или false если нет. Т.е. видимость метода, в конкретном применении вообще не проверяется. Поэтому, если вы используете private или protected методы, то такая проверка вернет true, но когда вы попытаетесь вызвать такой код, то увидите следующую ошибку

Правильный инструмент для правильной работы

Реальная цель предыдущего кода, была в том, чтобы определить, может ли данный метод быть вызван в данном контексте

Поэтому верно будет использовать is_callable() функцию php

Как это работает?

Следующий кусок кода илюстрирует разницу между работой двух функций method_exists() и is_callable() в действии:

Запустите это, и вы увидите, что все тесты вернули true при использовании method_exists(), даже private методы, тогда как is_callable() вернул FALSE

Больше деталей

Все остальное вы можете узнать, в PHP документации.

php check method exists. Смотреть фото php check method exists. Смотреть картинку php check method exists. Картинка про php check method exists. Фото php check method exists

Платная консультация по вопросам 2500 руб/час

Прочитали статью и остались вопросы? Меня зовут Валерий и я её автор. С радостью объясню Вам в скайпе все затруднительные моменты, которые остались за рамками статьи!

Источник

property_exists

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

property_exists — Проверяет, содержит ли объект или класс указанный атрибут

Описание

Функция проверяет, существует ли атрибут property в указанном классе.

Список параметров

Имя класса или объект класса для проверки

Возвращаемые значения

Примеры

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

Примечания

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс ещё не известен.

Смотрите также

User Contributed Notes 10 notes

The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()

$testObject = new TestClass ;

If you want to test if declared *public* property was unset, you can use the following code:

As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

[before-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)

[after-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)

[before-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)

[after-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(true)
[my_assigned_null]: bool(true)

[after-unset] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *