Home  >  Article  >  Backend Development  >  Detailed explanation of __isset() method in PHP

Detailed explanation of __isset() method in PHP

藏色散人
藏色散人Original
2019-07-22 13:21:3215828browse

__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:

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

The running results are as follows:

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

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!

Statement:
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