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

Detailed explanation of __unset() method in PHP

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

__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);
Copy after login

Running result:

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

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!

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