批改状态:合格
老师批语:
类代码:
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/5/3 0003
* Time: 下午 4:52
*/
class Computer
{
private $name;
private $price;
private $dress;
private $data=[];
public function __construct($name='',$price=0,$dress=''){
$this->name=$name;
$this->price=$price;
$this->dress=$dress;
}
public function __set($name,$value){
return isset($this->$name)?$this->$name = $value:$this->data[$name] = $value;
}
public function __get($name){
$msg=null;
if(isset($this->$name)){
$msg=$this->$name;
}elseif (isset($this->data[$name])){
$msg=$this->data[$name];
}else{
$msg ='不存在该数据!';
}
return $msg;
}
}点击 "运行实例" 按钮查看在线实例
前端代码:
<?php
require 'Computer.php';
$Computer=new Computer('dell',7000,'usa');
//魔术方法__get
echo '品牌:',$Computer->name,'<br>';
echo '价格:',$Computer->price,'<br>';
echo '产地:',$Computer->dress,'<br>';
echo '保修:',$Computer->repair;
echo '<hr>';
//魔术方法__set
$Computer->name='asus';
$Computer->price=6000;
$Computer->dress='China';
echo '品牌:',$Computer->name,'<br>';
echo '价格:',$Computer->price,'<br>';
echo '产地:',$Computer->dress,'<br>';
$Computer->color='black';
echo '颜色:',$Computer->color,'<br>';
echo '颜色:(自定义属性)',print_r($Computer->data);点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号