Using PHP is_object() to Determine if a Variable Is an Object

This article explains PHP's is_object() function, its syntax, parameters, return values, and provides example code demonstrating how to check whether variables such as objects and arrays are objects, along with the resulting output and a brief interpretation.

php Courses
php Courses
php Courses
Using PHP is_object() to Determine if a Variable Is an Object

Overview:

In PHP, is_object() function is used to check whether a variable is an object.

Syntax:

bool is_object (mixed $var)

Parameters:

$var: the variable to be checked.

Return Value:

Returns true if $var is an object; otherwise returns false.

Example Code:

// Define a class
class Person {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }
}

// Create object
$person = new Person('John');

// Check object variable
if (is_object($person)) {
    echo '变量$person是一个对象';
} else {
    echo '变量$person不是一个对象';
}

// Define an array
$fruit = array('apple', 'banana', 'orange');

// Check array variable
if (is_object($fruit)) {
    echo '变量$fruit是一个对象';
} else {
    echo '变量$fruit不是一个对象';
}

Output:

变量$person是一个对象
变量$fruit不是一个对象

Explanation:

The code first defines a Person class with a public property $name and a constructor. An instance $person is created with the name 'John'. Using is_object() on $person returns true, so the message indicates it is an object.

Next, an array $fruit is defined. Since $fruit is an array, is_object() returns false, and the message indicates it is not an object.

Conclusion:

The is_object() function can be used to verify whether a variable is an object, helping to avoid type errors at runtime.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

php-functionsis_objectobject-check
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.