PHP魔术方法__unset()

2018-09-16 23:00 By "Powerless" 3116 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

  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20