php проверка на класс
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.
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)
get_class
(PHP 4, PHP 5, PHP 7, PHP 8)
get_class — Возвращает имя класса, к которому принадлежит объект
Описание
Список параметров
Тестируемый объект. Внутри класса этот параметр может быть опущен.
Возвращаемые значения
Если параметр object опущен внутри класса, будет возвращено имя этого класса.
Если параметр object является экземпляром класса, существующего в пространстве имён, то будет возвращено полное имя с указанием пространства имён.
Ошибки
Список изменений
Версия | Описание |
---|---|
7.2.0 | До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удалён как значение по умолчанию для object и больше не является допустимым значением. |
Примеры
Пример #1 Использование get_class()
// создание объекта
$bar = new foo ();
Результат выполнения данного примера:
Пример #2 Использование get_class() в родительском классе
class foo extends bar <
>
Результат выполнения данного примера:
Пример #3 Использование get_class() с классами в пространствах имён
namespace Foo \ Bar ;
class Baz <
public function __construct ()
<
$baz = new \ Foo \ Bar \ Baz ;
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 36 notes
::class
fully qualified class name, instead of get_class
namespace my \ library \ mvc ;
print Dispatcher ::class; // FQN == my\library\mvc\Dispatcher
$disp = new Dispatcher ;
(For reference, here’s the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:
class Foo
<
public function __construct ()
<
echo «Foo» ;
>
>
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.
Here’s a good example that should fix that for ever:
class Bar extends Foo <
$foo = new Foo ();
$bar = new Bar ();
$quux = new Quux ();
—doMethod—
Foo::doMethod
Foo::doMethod
Quux::doMethod
—doGetClassThis—
Foo::doThat
Bar::doThat
Quux::doThat
—doGetClass—
Foo::doThat
Foo::doThat
Quux::doThat
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not ‘know’ the name of the calling subclass’, so I use a backtrace to determine it. I don’t like hacks like this, but as long as PHP doesn’t have an alternative, this is what has to be done:
Simplest way how to gets Class without namespace
namespace a \ b \ c \ d \ e \ f ;
echo new Foo (); // prints Foo
?>
Need a quick way to parse the name of a class when it’s namespaced? Try this:
/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) <
$classname = get_class($obj);
With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.
namespace Foo \ Bar ;
class Snafu extends Baz
<
>
__CLASS__ Foo\Bar\Baz Baz
get_called_class Foo\Bar\Snafu Snafu
The code in my previous comment was not completely correct. I think this one is.
/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() <
$implementing_class = static::$__CLASS__;
$original_class = __CLASS__;
There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.
private function __construct () <
// Singleton
>
>
class MySubclass extends MySuperclass <
>
Although you can call a class’s static methods from an instance of the class as though they were object instance methods, it’s nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():
If you want the path to an file if you have i file structure like this
and foo() in foo.php extends controller() in controller.php like this
namespace system \ modules \ foo ;
class foo extends \ system \ libs \ controller <
public function __construct () <
parent :: __construct ();
>
>
?>
and you want to know the path to foo.php in controller() this may help you
namespace system \ libs ;
well, if you call get_class() on an aliased class, you will get the original class name
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it’s not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().
default: throw new Exception ( «Unknown backtrace method type» );
>
>
>
class B extends Singleton <
>
class C extends Singleton <
>
Method for pulling the name of a class with namespaces pre-stripped.
namespace testme \ here ;
public function test ()
<
return get_class_name ( get_class ());
>
>
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the «self» keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the «self» keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:
public static function classDisplayName ()
<
return ‘Base Class’ ;
>
public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>
However, assuming compile-time binding (where the keyword «self» refers to the class in which the method is defined), which is how php works, the output would be:
The oddity here is that «$this» is bound at runtime to the actual class of the object (obviously) but «self» is bound at compile-time, which seems counter-intuitive to me. «self» is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which «self» ought to be useful.
However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to «self» being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the «self» keyword for static methods:
public static function classDisplayName ()
<
return ‘Base Class’ ;
>
public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>
I realise that some people might respond «why don’t use just just the class name with ‘ Class’ appended instead of the classDisplayName() method», which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.
Apologies if this has been mentioned before.
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’ ;
Оператор проверки типа
Оператор instanceof используется для определения того, является ли текущий объект экземпляром указанного класса.
Пример #1 Использование instanceof с классами
class NotMyClass
<
>
$a = new MyClass ;
Результат выполнения данного примера:
Оператор instanceof также может быть использован для определения, наследует ли определенный объект какому-либо классу:
Пример #2 Использование instanceof с наследуемыми классами
class MyClass extends ParentClass
<
>
Результат выполнения данного примера:
Для проверки непринадлежности объекта некоторому классу, используйте логический оператор not.
Пример #3 Использование instanceof для проверки того, что объект не является экземпляром класса
Результат выполнения данного примера:
Ну и наконец, instanceof может быть также использован для проверки реализации объектом некоторого интерфейса:
Пример #4 Использование instanceof для класса
class MyClass implements MyInterface
<
>
Результат выполнения данного примера:
Хотя instanceof обычно используется с прямо указанным именем класса, он также может быть использован с другим объектом или строковой переменной:
Пример #5 Использование instanceof с другими переменными
class MyClass implements MyInterface
<
>
$a = new MyClass ;
$b = new MyClass ;
$c = ‘MyClass’ ;
$d = ‘NotMyClass’ ;
Результат выполнения данного примера:
Пример #6 Пример использования оператора instanceof для проверки других переменных
Результат выполнения данного примера:
Есть несколько подводных камней, которых следует остерегаться. До версии PHP 5.1.0, instanceof вызывал __autoload() если имя класса не существовало. Вдобавок, если класс не был загружен, происходила фатальная ошибка. Это можно было обойти с помощью динамической ссылки на класс или использования строковой переменной с именем класса:
Пример #7 Избежание поиска класса и фатальных ошибок с instanceof в PHP 5.0
Результат выполнения данного примера: