php object property 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)
Check if a property exists on magically set properties
There is a lot of SO questions about the subject, notably this one, but it does not help me.
There is an ambiguity between property_exists and isset so before asking my question, I’m going to pointing it out:
property_exists
property_exists checks if an object contains a property without looking at its value, it only looks at its visibility.
So in the following example:
isset
isset and property_exists ‘s behaviour on magically added properties
A property can exist with a null value, so I can’t use __isset magic method to know if a property exist or not. I also can’t use property_exists as properties are added using magic methods.
Here is a sample, but this is just a sample because in my app, properties magically set are stored outside the object.
So here is my question :
2 Answers 2
I don’t believe there’s a way to alter the functionality of property_exists() using magic methods; here’s a list of available magic methods in PHP. However, you should be able to alter isset() to use any logic you like.
This effectively fixes the (annoying) problem with isset and nulls by overriding its functionality through the magic method. Instead of using isset() within __isset() however, we use array_key_exists (which handles nulls as you would expect). Thus __isset() returns the expected result when a null value is set.
This has a downside, namely that the overridden functionality does not produce the same results as default isset() functionality. So, if this object needs to be used transparently with other (perhaps stdClass) objects, then isset() will return true for null values in objects of this class, and false for null values in normal objects.
PHP check whether property exists in object or class
I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.
In JS, I can write this to check if variable a exists in an object:
In PHP, can anything like this be done?
9 Answers 9
isset() will return false if property is null
As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
Neither isset or property_exists work for me.
I ended up going with:
Solution
To show how this would look in an if statement for more clarity on how this is working.
Explanation
The traditional PHP way to check for something’s existence is to do:
OR for a more class specific way:
These are both fine in long form statements but in ternary statements they become unnecessarily cumbersome like so:
You can also achieve this with just the ternary operator like so:
But. if the value does not exist (is not set) it will raise an E_NOTICE and is not best practise. If the value is null it will not raise the exception.
Therefore ternary operator to the rescue making this a neat little answer:
property_exists
property_exists — Проверяет, содержит ли объект или класс указанный атрибут
Описание
Функция проверяет, существует ли атрибут property в указанном классе.
Список параметров
Имя класса или объекта класса для проверки
Возвращаемые значения
Примечания
Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.
Функция property_exists() не определяет магически доступные свойства с помощью метода __get.
Список изменений
Версия | Описание |
---|---|
5.3.0 | Эта функция проверяет существование свойства вне зависимости от его доступности. |
Примеры
Пример #1 Пример использования property_exists()
Смотрите также
Коментарии
As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.
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 ;
OUTPUT:
stdClass Object
(
[0] => a
[b] => c
)
bool(false)
bool(true)
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)
If you want to test if declared *public* property was unset, you can use the following code: