'Notice: Undefined property - how do I avoid that message in PHP?
Hello I am making this call:
$parts = $structure->parts;
Now $structure only has parts under special circumstances, so the call returns me null. Thats fine with me, I have a if($parts) {...} later in my code. Unfortunately after the code finished running, I get this message:
Notice: Undefined property: stdClass::$parts in ...
How can I suppress this message?
Thanks!
Solution 1:[1]
The function isset
should do exactly what you need.
Example:
$parts = (isset($structure->parts) ? $structure->parts : false);
Solution 2:[2]
Landed here in 2020 and surprised that noone has mentioned:
$parts = $structure->parts ?? false;
2.A frowned-upon practice - the stfu operator:
$parts = @$structure->parts;
Solution 3:[3]
maybe this
$parts = isset($structure->parts) ? $structure->parts : false ;
Solution 4:[4]
With the help of property_exists() you can easily remove "Undefined property" notice from your php file.
Following is the example:
if(property_exists($structure,'parts')){
$parts = $structure->parts;
}
To know more http://php.net/manual/en/function.property-exists.php
Solution 5:[5]
I have written a helper function for multilevel chaining. Let's say you want to do something like $obj1->obj2->obj3->obj4
, my helper function returns empty string whenever one of the tiers is not defined or null, so instead of $obj1->obj2->obj3->obj4
you my use MyUtils::nested($obj1, 'obj2', 'obj3', 'obj4')
. Also using this helper method will not produce any notices or errors. Syntactically it is not the best, but practically very comfortable.
class MyUtils
{
// for $obj1->obj2->obj3: MyUtils::nested($obj1, 'obj2', 'obj3')
// returns '' if some of tiers is null
public static function nested($obj1, ...$tiers)
{
if (!isset($obj1)) return '';
$a = $obj1;
for($i = 0; $i < count($tiers); $i++){
if (isset($a->{$tiers[$i]})) {
$a = $a->{$tiers[$i]};
} else {
return '';
}
}
return $a;
}
}
Solution 6:[6]
You can turn this off in the php.ini file.. you want to turn off E_NOTICE on the error_reporting flag.
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE
Whether it is wise to do this is another question (to which I suspect the answer is no).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nitram |
Solution 2 | Aydin4ik |
Solution 3 | Pedro Fillastre |
Solution 4 | Vishal |
Solution 5 | Mamed Shahmaliyev |
Solution 6 | demented hedgehog |