__unset 删除非公有属性,在外部调用unset时发生, __isset用来检测对象属性是否设置值
<?php
class coach
{
protected $chairfit = "徐晓冬";
protected $lover = "丁大锅";
public function __construct()
{
echo "欢迎来到~必图拳馆训练~";
}
public function __get($chairfit)
{
return $this->$chairfit;
}
public function __set($name,$value)
{
$this->$name=$value;
}
}
class cj extends coach
{
public $expertin = ['散打','泰拳','巴西柔术'];
}
$cj = new cj();
var_dump($cj);
$cj->lover='陈培昌';
var_dump(isset($cj->lover)) ;
?>
以为这样就能检测非公有属性是否设置?deeply sorry about that!
输出结果:
欢迎来到~必图拳馆训练~
bool(false)
正确姿势 <?php class coach { protected $chairfit = "徐晓冬"; protected $lover = "丁大锅"; public function __construct() { echo "欢迎来到~必图拳馆训练~"." "; } public function __get($chairfit) { return $this->$chairfit; } public function __set($name,$value) { $this->$name=$value; }
#加上这段 public function __isset($name) { return isset($name); } } class cj extends coach { public $expertin = ['散打','泰拳','巴西柔术']; } $cj = new cj(); //var_dump($cj); $cj->lover='陈培昌'; var_dump(isset($cj->lover)) ; ?>
输出结果:
欢迎来到~必图拳馆训练~
bool(true)
<?php
class coach
{
protected $chairfit = "徐晓冬";
private $lover;
public function __construct()
{
echo "欢迎来到~必图拳馆训练~"."
";
}
public function __get($chairfit)
{
return $this->$chairfit;
}
public function __set($name,$value)
{
$this->$name=$value;
}
public function __isset($name)
{
return isset($name);
}
public function __unset($name)
{
unset($this->$name);
}
}
class cj extends coach
{
public $expertin = ['散打','泰拳','巴西柔术'];
}
$cj = new coach();
//var_dump($cj);
$cj->lover='陈培昌';
var_dump($cj);
unset($cj->lover);
var_dump($cj);
?>
unset cj对象的lover属性之前,打印对象结果为:
object(coach)#1 (2) {
["chairfit":protected]=>
string(9) "徐晓冬"
["lover":"coach":private]=>
string(9) "陈培昌"
}
删除之后打印对象结果
object(coach)#1 (1) {
["chairfit":protected]=>
string(9) "徐晓冬"
}