20

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,975
  • 17
  • 43
  • 70

7 Answers7

38

The function isset should do exactly what you need.

PHP: isset - Manual

Example:

$parts = (isset($structure->parts) ? $structure->parts : false);
Nitram
  • 6,486
  • 2
  • 21
  • 32
12

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,782
  • 1
  • 14
  • 19
6

maybe this

$parts = isset($structure->parts) ? $structure->parts : false ;
Pedro Fillastre
  • 892
  • 6
  • 10
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

linktoahref
  • 7,812
  • 3
  • 29
  • 51
Vishal
  • 639
  • 7
  • 32
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;
    }
}
-1

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
  • 7,007
  • 4
  • 42
  • 49
-1

use @ before access to suppress warnings & errors inline:

$v=@$object->field->subfield;

note This is a bad practice, but it will do the trick

Luca C.
  • 11,714
  • 1
  • 86
  • 77