How to Use PHP’s is_object() to Distinguish Objects from Other Types
This article explains PHP’s is_object() function, detailing its syntax, parameters, and return values, and demonstrates through code examples how to check whether variables such as objects and arrays are objects, helping developers avoid type errors at runtime.
Overview
In PHP, the 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 an object
$person = new Person('John');
// Check object variable
if (is_object($person)) {
echo 'Variable $person is an object';
} else {
echo 'Variable $person is not an object';
}
// Define an array
$fruit = array('apple', 'banana', 'orange');
// Check array variable
if (is_object($fruit)) {
echo 'Variable $fruit is an object';
} else {
echo 'Variable $fruit is not an object';
}Output
Variable $person is an object
Variable $fruit is not an objectExplanation
The code first defines a Person class with a public property $name and a constructor __construct(). An instance $person is created with the name “John”. Using is_object() on $person returns true, so the script outputs that $person is an object.
Next, an array $fruit is defined. Since $fruit is an array, is_object() returns false, and the script outputs that $fruit is not an object.
Conclusion
The is_object() function can be used to verify whether a variable is an object, allowing developers to ensure correct variable types at runtime and avoid unexpected type errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
