15

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!

EOB
  • 2,887
  • 17
  • 42
  • 68

6 Answers6

35

The function isset should do exactly what you need.

PHP: isset - Manual

Example:

$parts = (isset($structure->parts) ? $structure->parts : false);
Nitram
  • 6,166
  • 2
  • 20
  • 31
6

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;
Aydin4ik
  • 1,634
  • 1
  • 11
  • 17
5

maybe this

$parts = isset($structure->parts) ? $structure->parts : false ;
Pedro Fillastre
  • 812
  • 5
  • 9
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

Vishal
  • 796
  • 6
  • 28
1

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;
    }
}
0

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).

demented hedgehog
  • 6,371
  • 3
  • 39
  • 48