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.
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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.