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

Detailed explanation of __unset() method in PHP

藏色散人
藏色散人Original
2019-07-23 14:52:176951browse

__unset(), called when unset() is called on an inaccessible property.

Before looking at this method, let’s take a look at the unset() function. The function of unset() is to delete the specified variable and return true. The parameter is the variable to be deleted.

So if you want to delete the member attributes inside the object outside an object, can you use the unset() function?

There are naturally two situations here:

1. If the member attributes in an object are public, you can use this function to delete the object outside the object. Public properties.

2. If the member attributes of the object are private, I will not have permission to delete them using this function.

Although there are the above two situations, what I want to say is that if you add the __unset() method to an object, you can delete the private member attributes of the object outside the object. After adding the __unset() method to the object, when using the "unset()" function outside the object to delete the private member attributes inside the object, the object will automatically call the __unset() function to help us delete the private member attributes inside the object. Member properties.

Please see the following code:

<?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 __unset($content) {
        echo "当在类外部使用unset()函数来删除私有成员时自动调用的<br>";
        echo  isset($this->$content);
    }
}
$person = new Person("小明", 25); // 初始赋值
unset($person->sex);
unset($person->name);
unset($person->age);

Running result:

当在类外部使用unset()函数来删除私有成员时自动调用的
1当在类外部使用unset()函数来删除私有成员时自动调用的
1

The above is the detailed content of Detailed explanation of __unset() 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
Previous article:TP5 (layui) excel importNext article:TP5 (layui) excel import