<?
/**
* @description 类中魔术方法的定义
* @package null
* @version 1.0.0
*/
class Test {
private $name;
private $age;
public function __construct($name = null, $age = null) {
$this->name = $name;
$this->age = $age;
}
/**
* 判断属性在该类中是否存在
* @param string $propertyName 属性名称
*/
private function isPropertyExists($propertyName) {
$properties = get_class_vars(get_class($this));
if (!array_key_exists($propertyName, $properties)) {
echo '属性值' . $propertyName . '不存在';
exit();
}
}
public function __set($propertyName, $propertyValue) {
$this->isPropertyExists($propertyName);
$this->$propertyName = $propertyValue;
}
public function __get($propertyName) {
$this->isPropertyExists($propertyName);
return $this->$propertyName;
}
public function __toString() {
return $this->name . PHP_EOL . $this->age;
}
}
6. 类中魔术方法的使用
最新推荐文章于 2025-04-14 14:11:10 发布