php里isset的属性,PHP魔术方法__isset()
在對象外部使用isset()方法有兩種情況:
如果參數(shù)是公有屬性,那么可以利用isset()方法判斷屬性是否被設(shè)置;
如果參數(shù)是私有屬性,isset()方法將無法使用。
那么,是否有辦法判斷私有屬性被設(shè)置呢?當(dāng)然,只需要在類里定義__isset()方法,就可以在對象外部利用isset()方法判斷某個私有屬性是否被設(shè)置了。
對未定義或沒有權(quán)限訪問的屬性調(diào)用isset()或empty()時,就會調(diào)用__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),"
";
輸出結(jié)果如下:
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
總結(jié)
以上是生活随笔為你收集整理的php里isset的属性,PHP魔术方法__isset()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 供应链 信用管理 大数据_智慧供应链大数
- 下一篇: Python学习笔记:Day 6 配置文