PHP魔术方法__isset()

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

  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • MySQL分组
    Posted on 2019-11-18 14:00
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03