<?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);
封装性和魔术方法
最新推荐文章于 2023-08-30 21:56:06 发布