2022/7/18 魔术方法之 `__set`
文章目录
魔术方法之 __set
一、__set
(一)调用时机
设置一个类的成员变量时调用。
(二)用途
- 用来在类的外部设置私有属性的值。
- 给一个未定义的属性赋值。
(三)例子
<?php
class User{
private $name;
private $age;
public function __set($property,$val){
switch($property){
case 'name':
$this->name = $val;
break;
case 'age':
$this->age = $val;
break;
default:
$this->$property = $val;
break;
}
}
public function getProperty($property){
return isset($this->$property) ? $this->$property : $property.' 属性不存在!';
}
}
$user = new User();
$user->name = 'Moonshadow';
echo $user->getProperty('name')."\n"; // Moonshadow
echo $user->getProperty('weight')."\n"; // weight 属性不存在!
$user->weight = 'unknow';
echo $user->getProperty('weight'); // unknow分析:当给私有属性 name 赋值时,__set 方法被调用。
(四)注意
__set方法的参数有且只能是2个,一个是属性名,一个是属性要设置的值。
多了少了都会报错。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论