PHP function introduction—is_object(): Check whether the variable is an object

WBOY
Release: 2023-07-25 10:48:01
Original
1445 people have browsed it

PHP function introduction - is_object(): Check whether a variable is an object

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: variable to check

Return value:
If $ If var is an object, return true; otherwise, return false.

Sample code:

// 定义一个类
class Person {
    public $name;

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

// 创建对象
$person = new Person('John');

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

// 定义一个数组
$fruit = array('apple', 'banana', 'orange');

// 检查数组变量
if (is_object($fruit)) {
    echo '变量$fruit是一个对象';
} else {
    echo '变量$fruit不是一个对象';
}
Copy after login

Output result:

变量$person是一个对象
变量$fruit不是一个对象
Copy after login

Explanation:
In the above code, first we define a class named Person, which has A public property $name and a constructor function __construct(). Then we create a $person object using the new keyword and pass in 'John' as a constructor parameter. As a first example, we use the is_object() function to check the $person variable. Since it is an object, the final output is "The variable $person is an object".

Next, we define an array variable called $fruit and try to check it using the is_object() function. Since the $fruit variable is an array, not an object, the final output is "Variable $fruit is not an object".

Conclusion:
The is_object() function can be used to check whether a variable is an object. By using this function, we can ensure the type of the variable at runtime, thus avoiding unexpected type errors.

The above is the detailed content of PHP function introduction—is_object(): Check whether the variable is an object. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!