php проверить наличие класса

class_exists

class_exists — Проверяет, был ли объявлен класс

Описание

Эта функция проверяет, был ли объявлен указанный класс или нет.

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

Имя класса. Воспринимается без учета регистра.

Вызывать ли по умолчанию __autoload.

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

Список изменений

Примеры

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

// Проверяем существование класса перед его использованием
if ( class_exists ( ‘MyClass’ )) <
$myclass = new MyClass ();
>

Пример #2 Пример использования параметра autoload

if ( class_exists ( ‘MyClass’ )) <
$myclass = new MyClass ();
>

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

Коментарии

If you have a directory of classes you want to create. (Modules in my instance). you can do it like that

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.

I’m running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn’t exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

use a\namespaced\classname as coolclass;

class_exists( ‘coolclass’ ) => false

Beware: class_exists is case-INsensitive, as is class instantiation.

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.

Источник

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)

Источник

class_exists

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

class_exists — Проверяет, был ли объявлен класс

Описание

Эта функция проверяет, был ли объявлен указанный класс или нет.

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

Имя класса. Воспринимается без учёта регистра.

Вызывать ли по умолчанию __autoload.

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

Примеры

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

// Проверяем существование класса перед его использованием
if ( class_exists ( ‘MyClass’ )) <
$myclass = new MyClass ();
>

Пример #2 Пример использования c параметром autoload

if ( class_exists ( MyClass ::class)) <
$myclass = new MyClass ();
>

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

User Contributed Notes 9 notes

use a\namespaced\classname as coolclass;

class_exists( ‘coolclass’ ) => false

If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.

Beware: class_exists is case-INsensitive, as is class instantiation.

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

I’m running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn’t exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

If you have a directory of classes you want to create. (Modules in my instance). you can do it like that

If spl_autoload_register() had been called, then function will try autoload class if it does not 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 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_a — Проверяет, принадлежит ли объект к данному классу или является ли этот класс одним из его родителей

Описание

Проверяет, принадлежит ли объект object_or_class к данному классу или является ли этот класс одним из его родителей.

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

Имя класса или объект

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

Примеры

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

// создание нового объекта
$WF = new WidgetFactory ();

Пример #2 Использование оператора instanceof

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

User Contributed Notes 7 notes

Please note that you have to fully qualify the class name in the second parameter.

A use statement will not resolve namespace dependencies in that is_a() function.

namespace foo \ bar ;

class A <>;
class B extends A <>;
?>

namespace har \var;

use foo \ bar \ A ;
$foo = new foo \ bar \ B ();

Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a(’23’, ‘User’); will trigger __autoload() on «23». Previously, the above statement simply returned ‘false’.

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now.

At least in PHP 5.1.6 this works as well with Interfaces.

interface test <
public function A ();
>

class TestImplementor implements test <
public function A () <
print «A» ;
>
>

$testImpl = new TestImplementor ();

is_a returns TRUE for instances of children of the class.

class Dog extends Animal
<>

In this example is_a($test, «Animal») would evaluate to TRUE as well as is_a($test, «Dog»).

This seemed intuitive to me, but did not seem to be documented.

It took some time to find out how the last parameter should be used. Please consider the following example

I just want to point out that you can replace «is_a()» function with the «instanceof» operator, BUT you must use a variable to pass the class name string.

This will work:
= new \ stdClass ();
$class_name = ‘\stdClass’ ;

Источник

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

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