<?php
/**
* PHP在面向对方方面的一个很灵活的特性就是运行时刻成员变更的定义与使用。
* 这种特征带来的操作上的方便性,但也非常的不规范,会导致与设计不符合或是滥用。
* 因此PHP又提供了__get 与 __set方法来对运行时刻的这种特性进行限制的手段,称为魔术方法。
* 其主要目的就是为了控制这种动态的行为。
* @author www.phpchengdu.com 罗维
*/
class student{
private $name;
private $key_value=array();
public function setName($name){
$this->name=$name;
return true;
}
public function getName(){
return $this->name;
}
public function __set($key,$value){
echo "你不能在运行时刻定义动态的成员变量";
exit();
/* echo "<br />";
echo 'key is '.$key;
echo 'value is '.$value;*/
if($key=='age'){
if($value<0){
echo "出错了";
exit();
}
}
$this->key_value[$key]=$value;
}
public function __get($key){
return $this->key_value[$key];
}
}
$one=new student();
$one->setName('mike');
echo $one->getName();
$one->age=-1;
echo $one->age;
//$one->setAge('18');

