您的位置:首页 > 其它

封装性和魔术方法

2015-12-25 19:58 387 查看
<?php
class person{
public $name;
private $age;
protected $sex;

public function __construct($name, $age, $sex){
$this -> name = $name;
$this -> age = $age;
$this -> sex = $sex;
}

public function __set($name, $value){
if($name == 'age' && $value > 30){
$this -> $name = 10;
}else{
$this -> $name = 5;
}
}

public function __get($name){
if($name == 'sex'){
if($this -> $name == 'w'){
return "{$this -> name} is a woman!";
}else{
return "{$this -> name} is a man!";
}
}
return $this -> $name;
}

public function __isset($name){
if($name == 'age'){
return true;
}
}

public function __unset($name){
unset($this -> $name);
}
}

$person = new person("zhangsan", 18, 'w');
$person -> age = 20; //__set()
echo $person -> age; //__get()
echo "<hr />";
echo $person -> sex; //__get()
echo "<hr />";
var_dump(isset($person -> name)); //isset()做出判断,true or false。如果不存在这个属性或存在属性但未初始化(NULL),就返回false。
var_dump(isset($person -> age)); //__isset()
unset($person -> age); //__unset()
echo "<hr />";
var_dump($person);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: