Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 730
EOB Avatar asked Apr 13 '12 14:04

EOB


People also ask

How can avoid undefined offset in PHP?

This error means that within your code, there is an array and its keys. But you may be trying to use the key of an array which is not set. The error can be avoided by using the isset() method.

What is the meaning of undefined offset in PHP?

The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.

What is offset in PHP?

It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.

What is undefined in PHP?

There are two methods in PHP called $_POST and $_GET methods which are used to obtain the input from the user while using a form. While using forms in PHP, if there is any variable or constant with no values assigned to them, then an error is encountered called undefined index in a manner “Notice: Undefined index” .


4 Answers

The function isset should do exactly what you need.

PHP: isset - Manual

Example:

$parts = (isset($structure->parts) ? $structure->parts : false);
like image 159
Nitram Avatar answered Oct 23 '22 07:10

Nitram


maybe this

$parts = isset($structure->parts) ? $structure->parts : false ;
like image 29
Pedro Fillastre Avatar answered Oct 23 '22 06:10

Pedro Fillastre


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;
like image 10
Aydin4ik Avatar answered Oct 23 '22 08:10

Aydin4ik


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

like image 4
Vishal Avatar answered Oct 23 '22 06:10

Vishal