
批改狀態(tài):合格
老師批語:
<?php
/**
* 1.屬性重載:__get(),set__()
* 2.方法屬性:__call(),__callStatic()
*/
class User
{
// 屬性
private $data = ['age'=>20];
//查詢攔截器
public function __get($name){
//$name:屬性名
// return $this->name;
if (array_key_exists($name,$this->data)) {
return $this->data[$name];
}
return "屬性{$name}不存在";
}
//更新攔截器
public function __set($name,$value)
{
//1.有沒有這個(gè)屬性?
if (array_key_exists($name,$this->data)){
//2.這個(gè)值是否合法?
if ($name === 'age') {
if ($value>=18 && $value<=59) {
$this->data[$name] = $value;
} else {
echo '年齡必須在18-59歲之間';
}
} else {
// 以上操作僅對(duì)age有效,其它屬性值直接賦值
$this->data[$name] = $value;
}
} else {
echo '禁止動(dòng)態(tài)創(chuàng)建屬性';
}
}
//方法攔截器
public function __call($name,$args){
// $name:方法名,$args:傳給方法的參數(shù)
printf('方法:%s<br>參數(shù):<pre>%s</pre>',$name,print_r($args,true));
}
//靜態(tài)方法攔截器
public static function __callStatic($name,$args){
// $name:方法名, $args:傳給方法的參數(shù)
printf('方法:%s<br>參數(shù):<pre>%s</pre>',$name,print_r($args,true));
}
}
$user = new User;
echo $user->name.'<br>';
/**
* 為一個(gè)屬性賦值的時(shí)候,必須要搞清楚2件事
* 1. 有沒有這個(gè)屬性?
* 2. 這個(gè)值是否合法?
*/
$user->age = 29;
echo $user->age.'<br>';
echo '<hr>';
// 常規(guī)方法/非靜態(tài)方法/用實(shí)例調(diào)用
$user->hello('豬老師', 'php.cn');
echo '<hr>';
// 靜態(tài)方法
User::world(100,200);
運(yùn)行后效果如下:
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)