PHP魔术方法__isset()

2018-09-16 19:00 By "Powerless" 3089 0 1

在对象外部使用isset()方法有两种情况:

    如果参数是公有属性,那么可以利用isset()方法判断属性是否被设置;

    如果参数是私有属性,isset()方法将无法使用。

那么,是否有办法判断私有属性被设置呢?当然,只需要在类里定义__isset()方法,就可以在对象外部利用isset()方法判断某个私有属性是否被设置了。

对未定义或没有权限访问的属性调用isset()或empty()时,就会调用__isset()方法。

示例代码如下:

<?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 __isset($content) {
        echo "The {$content} property is private,the __isset() method is called automatically.<br>";
        echo  isset($this->$content);
    }
}
$person = new Person("John", 25); // 赋初始值
echo isset($person->sex),"<br>";
echo isset($person->name),"<br>";
echo isset($person->age),"<br>";

输出结果如下:

1
The name property is private,the __isset() method is called automatically.
1
The age property is private,the __isset() method is called automatically.
1


评 论

View in WeChat

Others Discussion

  • 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
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • 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