__call 当要调用的方法不存在或权限不足时,会自动调用__call方法。__callStatic 当调用的静态方法不存在或权限不足时,会自动调用__callStatic方法。 该方法在本类中测试是不能用的,必须在别的类中调用本类的方法才可以。
__call 方法测试:
<?phpclass Memeber
{
//保存定义参数和值
protected $memberdata = array();
public function __call($func ,$arguments) {
//方法调用时仅过滤set_xxx 或get_xxx 的方法
list($type,$name) = explode('_',$func);
if(!in_array($type,array('set','get'))||$name=='') {
return '';
}
switch ($type) {
case 'set': //set 方法
$this->memberdata[$name] = $arguments[0];
break;
case 'get': //get 方法
return isset($this->memberdata[$name])?$this->memberdata[$name]:'';
break;
default:
# code...
break;
}
}
}
class User extends Memeber
{
public function show() {
if ($this->memberdata) {
foreach ($this->memberdata as $key => $memeber) {
echo $key.":".$memeber.PHP_EOL; //将数组中对应本类的key和value打印出来
}
}
}
}
class Profession extends Memeber
{
public function show() {
if ($this->memberdata) {
foreach ($this->memberdata as $key => $memeber) {
echo $key.':'.$memeber.PHP_EOL;
}
}
}
}
$user = new User();
$user->set_name('fdddss');
$user->set_age(22);
$user->show();
$pro = new Profession();
$pro->set_profession('IT SERVEICE');
$pro->set_price(2500);
$pro->show()
打印结果:
name:fdddss
age:22
profession:IT SERVEICE
price:2500
class Member
{
protected static $memberdata = array();
public static function __callStatic($func,$arguments) {
list($type,$name) = explode('_', $func);
if (!in_array($type, array('set','get'))||$name=='') {
return '';
}
$feature = get_called_class();
switch ($type) {
case 'set':
self::$memberdata[$feature][$name] = $arguments[0];
break;
case 'get':
return isset(self::$memberdata[$feature][$name])? self::memberdata[$feature][$name]:'';
break;
default:
# code...
break;
}
}
}
class User extends Member
{
public static function show() {
$feature = get_called_class();
if (self::$memberdata[$feature]) {
foreach (self::$memberdata[$feature] as $key => $memeber) {
echo $key.':'.$memeber.PHP_EOL;
}
}
}
}
class Profession extends Member
{
public static function show(){
$feature = get_called_class();
if(self::$memberdata[$feature]){
foreach(self::$memberdata[$feature] as $key=>$member){
echo $key.':'.$member.PHP_EOL;
}
}
}
}
User::set_name('fdipzone');
User::set_age(22);
User::show();
Profession::set_profession('IT SERVICE');
Profession::set_price(2500);
Profession::show();
打印结果:
name:fdipzone
age:22
profession:IT SERVICE
price:2500