This is a bit philosophical but I think many people encountered this problem. The goal is to access various (dynamically declared) properties in PHP and get rid of notices when they are not set.
Why not to __get
?
That's good option if you can declare your own class, but not in case of stdClass
, SimpleXML
or similar. Extending them is not and option since you usually do not instantiate these classes directly, they are returned as a result of JSON/XML parsing.
Example:
$data = '{"name": "Pavel", "job": "programmer"}';
$object = json_decode($data);
We have simple stdClass
object. The problems is obvious:
$b = $data->birthday;
The property is not defined and therefore a notice is raised:
PHP Notice: Undefined property: stdClass::$birthday
This can happen very often if you consider that you get that object from parsing some JSON. The naive solution is obvious:
$b = isset($data->birthday) ? $data->birthday : null;
However, one gets tired very soon when wrapping every accessor into this. Especially when chaining the objects, such as $data->people[0]->birthday->year
. Check whether people
is set. Check if the first element is set. Check if birthday
is set. Check if year
is set. I feel a bit overchecked...
Question:
Finally, my question is here.
What is the best approach to this issue? Silencing notices does not seem to be the best idea. And checking every property is difficult. I have seen some solutions such as Symfony property access but I think it is still too much boilerplate. Is there any simpler way? Either third party library, PHP setting, C extension, I don't care as far as it works... And what are the possible pitfalls?
The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object. When an object is made, it has some properties. An associative array of properties of the mentioned object is returned by the function. But if there is no property of the object, then it returns NULL.
Properties of Object Properties are variables that are defined within a class. These variables are then used by the methods, objects of the class. These variables can be public, protected or private. By default, the public is used.
How do you delete an object in PHP? An object is an instance of a class. Using the PHP unset() function, we can delete an object. So with the PHP unset() function, putting the object that we want to delete as the parameter to this function, we can delete this object.
Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP.
in PHP version 8
you can use Nullsafe
operator as follow:
$res = $data?->people[0]?->birthday?->year;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With