Detailed explanation of __isset() method in PHP

藏色散人
Release: 2023-04-07 06:28:01
Original
15807 people have browsed it

__isset(), called when isset() or empty() is called on an inaccessible property

Before looking at this method, let’s take a look at the application of isset() function, isset () is a function used to determine whether a variable is set. A variable is passed in as a parameter. If the passed variable exists, true is returned, otherwise false is returned.

So if you use the isset() function outside an object to determine whether the members inside the object are set, can you use it?

There are two situations. If the members in the object are public, we can use this function to measure the member attributes. If they are private member attributes, this function will not work. The reason is that they are private. It is encapsulated and not visible from the outside. So we can't use the isset() function outside the object to determine whether the private member attributes have been set? Of course it's possible, but it's not set in stone.

You only need to add an __isset() method to the class. When the isset() function is used outside the class to determine whether the private members in the object are set, the class will be automatically called. The __isset() method inside helps us complete such operations.

The role of __isset():

When isset() or empty() is called on an inaccessible property, __isset() will be called.

Please see the following code demonstration:

name = $name; $this->age = $age; $this->sex = $sex; } /** * @param $content * * @return bool */ public function __isset($content) { echo "当在类外部使用isset()函数测定私有成员{$content}时,自动调用
"; echo isset($this->$content); } } $person = new Person("小明", 25); // 初始赋值 echo isset($person->sex),"
"; echo isset($person->name),"
"; echo isset($person->age),"
";
Copy after login

The running results are as follows:

1 // public 可以 isset() 当在类外部使用isset()函数测定私有成员name时,自动调用 // __isset() 内 第一个echo 1 // __isset() 内第二个echo 当在类外部使用isset()函数测定私有成员age时,自动调用 // __isset() 内 第一个echo 1 // __isset() 内第二个echo
Copy after login

The above is the detailed content of Detailed explanation of __isset() method in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
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!