批改狀態(tài):合格
老師批語:
<?php //類的構造方法與查詢器與設置器 class LeiMing3 { //private:訪問控制符:私有的,必須在當前類中訪問,外部不能訪問 private $name = '二號'; private $age = 16; private $stature = [80,60,70]; private $yx = []; //聲明一個構造方法:在實例化類的時候自動調用 //構造方法也構造器:對象屬性的初始化 public function __construct($name,$age,array $stature){ $this->name = $name; $this->age = $age; $this->stature = $stature; } //查詢器獲取器,過濾外部訪問 public function __get($name){ $msg = null;//定義一個空值 if(isset($this->$name)){//判斷傳輸進來的屬性是否存在 $msg = $this->$name; }elseif(isset($this->yx[$name])){//判斷傳輸進來的屬性是否存在自定義中 $msg = $this->yx[$name]; }else{ $msg ='非法數(shù)據(jù)';//查不到該屬性 } return $msg; } public function __set($name,$value){ if(isset($this->$name)){//判斷屬性是否存在 $this->$name=$value;//存在接受屬性 }else{ $this->yx[$name]=$value;//不存在就保存自定義屬性 } }
<?php require 'LeiMing3.php'; $lm3 = new LeiMing3('3hao',28,[8,9,10]); //測試魔術方法__get() echo 'name: ',$lm3->name,'<br>'; echo 'age: ',$lm3->age, '<br>'; echo 'stature: ', print_r($lm3->stature,true), '<br>'; echo 'nothing:', $lm3->xxx, '<br>';//獲取一個不存在的屬性 //測試魔術方法: __set() $lm3->name = '12313'; $lm3->age = 111; $lm3->stature = [5,8,88]; echo 'name: ',$lm3->name,'<br>'; echo 'age: ',$lm3->age, '<br>'; echo 'stature: ', print_r($lm3->stature,true), '<br>'; $lm3->hobby = '購物';//自定義hobby屬性并賦值 echo 'custom:', $lm3->hobby, '<br>';//輸出自定義hobby屬性 $lm3->email = '123@.123asd';//自定義email屬性并賦值 echo 'custom:', $lm3->email, '<br>';//輸出自定義email屬性 ?>
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號