PHP Function Reference

PHP is_object() Function



The PHP is_object() function checks whether a variable is an object or not. The function returns true if the variable is an object, otherwise it returns false.

Syntax

is_object(variable)

Parameters

variable Required. Specify the variable being evaluated.

Return Value

Returns true if variable is an object, false otherwise.

Example:

The example below shows the usage of is_object() function.

<?php
$x = array(1, 2, 3);

var_dump(is_object(new ArrayIterator($x)));  //returns: bool(true)
var_dump(is_object(new ArrayIterator()));    //returns: bool(true)
var_dump(is_object(new stdClass()));         //returns: bool(true)

echo "\n";

var_dump(is_object(10));       //returns: bool(false)
var_dump(is_object('xyz'));    //returns: bool(false)
var_dump(is_object(true));     //returns: bool(false)
var_dump(is_object($x));       //returns: bool(false)
?>

The output of the above code will be:

bool(true)
bool(true)
bool(true)

bool(false)
bool(false)
bool(false)
bool(false)

Example:

Consider one more example to understand the concept of is_object() function.

<?php
//creating function to return colors 
//property of an object
function get_colors($x) {
  if (!is_object($x)) {
    return false;
  }

  return $x->colors;
}

//creating a new class instance and 
//defining its colors property
$obj = new stdClass();
$obj->colors = array('Red', 'Green', 'Blue');

var_dump(get_colors(null));
echo "\n";
var_dump(get_colors($obj));
?>

The output of the above code will be:

bool(false)

array(3) {
  [0]=>
  string(3) "Red"
  [1]=>
  string(5) "Green"
  [2]=>
  string(4) "Blue"
}

❮ PHP Variable Handling Reference