Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check whether property exists in object or class

I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.

$ob = (object) array('a' => 1, 'b' => 12); 

or

$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;

In JS, I can write this to check if variable a exists in an object:

if ('a' in ob)

In PHP, can anything like this be done?

like image 453
Micah Avatar asked Oct 07 '22 01:10

Micah


People also ask

How do you check if a key exists in an object PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How do you check if a variable is an object in PHP?

The is_object() function checks whether a variable is an object. This function returns true (1) if the variable is an object, otherwise it returns false/nothing.

How do you check if value exists in array of objects PHP?

The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .

How can handle undefined property in PHP?

With the help of property_exists() you can easily remove "Undefined property" notice from your php file.


1 Answers

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

NOTE : Mind that isset() will return false if property is null

if (isset($ob->a))

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false
like image 117
Peter Avatar answered Oct 18 '22 02:10

Peter