php里isset的属性,PHP魔术方法__isset()

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

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

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

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

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

示例代码如下:

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.
";

echo  isset($this->$content);

}

}

$person = new Person("John", 25); // 赋初始值

echo isset($person->sex),"
";

echo isset($person->name),"
";

echo isset($person->age),"
";

输出结果如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值