(__set(),__get(), 写个案例)
<?php
class person //人类
{
protected $name; //姓名
private $age;//年龄
private $sex;//性别
public function __set($name,$value)//设置保护或私有属性
{
if($name=='age') {
if ($value>0&&$value<120) {
$this->age=$value;
}else {echo '非法输入年龄:'.$value;
return; }
}
if($name=='sex') {
if ($value=='男'||$value=='女') {
$this->sex=$value;
}else {echo '请输入"男"或"女",性别不能为"'.$value.'"';
return; }
}
$this->$name=$value;
}
public function __get($name)//获取商品信息
{
return $this->$name;
}
}
$jj=new person;
$jj->name='小王';
echo $jj->name;
echo '<hr>';
$jj->age='啊';
echo $jj->age;
echo '<hr>';
$jj->sex='人妖';
echo $jj->sex;
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号