Blogger Information
Blog 28
fans 0
comment 0
visits 16652
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的构造方法,查询器,设置器--2018年05月04日00:58
植树青年小江同志的博客
Original
462 people have browsed it

类的代码

实例


<?php 

class Honda
{
  // 声明属性
  private $name;
  private $level;
  private $price;
   private $data=[];

  public function __construct($name='', $level='A0', $price=0)
  {
    $this->name = $name;
    $this->level = $level;
    $this->price = $price;
  }

  public function __set($name, $value)
  {
    if (isset($this->$name)) {
      $this->$name = $value;
    } else {
      //  如果属性不存在,则创建它并保存到类属性$data数组中
      $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 'class.php';

$Honda = new Honda('Accord','B',179800);

// 魔术方法__get
echo '名字:',$Honda->name,'<br>';
echo '级别:',$Honda->level,'<br>';
echo '售价:',$Honda->price,'<br>';
echo '<hr>';

// 魔术方法 __set
$Honda->name='Civic';
$Honda->level='A';
$Honda->price=139900;


echo '名字:',$Honda->name,'<br>';
echo '级别:',$Honda->level,'<br>';
echo '售价:',$Honda->price,'<br>';

$Honda->color='black';
echo '颜色:',$Honda->color,'<br>';
echo '颜色:(自定义属性)',print_r($Honda->data);

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post