-->

Notice: Undefined property - how do I avoid that m

2020-08-26 05:21发布

问题:

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!

回答1:

The function isset should do exactly what you need.

PHP: isset - Manual

Example:

$parts = (isset($structure->parts) ? $structure->parts : false);


回答2:

maybe this

$parts = isset($structure->parts) ? $structure->parts : false ;


回答3:

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



回答4:

Landed here in 2020 and surprised that noone has mentioned:

1.As of PHP 7.0:

$parts = $structure->parts ?? false;

2.A frowned-upon practice - the stfu operator:

$parts = @$structure->parts;