PHP魔术方法__unset()

2018-09-16 23:00 By "Powerless" 3119 0 1

未定义或无权限访问的属性上调用unset()方法时会触发__unset()方法。

示例代码如下:

<?php
class Person
{
    public $sex;
    private $name;
    private $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    /**
     * @param $content
     *
     * @return bool
     */
    public function __unset($content) {
        echo "It is called automatically when we use the unset() method outside the class.<br>";
        echo  isset($this->$content);
    }
}
$person = new Person("John", 25); // 赋初始值
unset($person->sex),"<br>";
unset($person->name),"<br>";
unset($person->age),"<br>";

输出结果如下:

It is called automatically when we use the unset() method outside the class.
1
It is called automatically when we use the unset() method outside the class.
1


评 论

View in WeChat

Others Discussion

  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03