Reputation: 3085
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?
Upvotes: 24
Views: 50088
Reputation: 12584
use @
before access to suppress warnings & errors inline:
$v=@$object->field->subfield;
note This is a bad practice, but it will do the trick
Upvotes: -1
Reputation: 742
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
Upvotes: 7
Reputation: 7548
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).
Upvotes: -1
Reputation: 333
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;
}
}
Upvotes: 1
Reputation: 1935
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;
Upvotes: 21
Reputation: 922
maybe this
$parts = isset($structure->parts) ? $structure->parts : false ;
Upvotes: 6
Reputation: 6716
The function isset
should do exactly what you need.
Example:
$parts = (isset($structure->parts) ? $structure->parts : false);
Upvotes: 43