国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

PHP魔術方法的使、用示例

2019-11-02 15:11:53
字體:
來源:轉載
供稿:網友

   這篇文章主要介紹了PHP魔術方法的使用示例,本文分別講解了__get、__set、__call、__callStatic、__toString、 __invoke等魔術方法的使用,需要的朋友可以參考下

  ① __get/__set:將對象的屬性進行接管

  當訪問一個不存在的對象屬性時:

  index.php

   代碼如下:

  

  define('BASEDIR',__DIR__); //定義根目錄常量

  include BASEDIR.'/Common/Loader.php';

  spl_autoload_register('CommonLoader::autoload');

  $obj = new CommonObject();

  //在php中訪問一個不存在的對象屬性時

  echo $obj->title;

  會拋出一個錯誤:Notice: Undefined property: CommonObject::$title in D:practisephpdesignpsr0index.php on line 9

  當在Common/Object.php 中添加 __set 和 __get 方法后

  Object.php

   代碼如下:

  

  namespace Common;

  class Object{

  function __set($key,$value){

  }

  function __get($key){

  }

  }

  再執行 index.php,不會再報錯。

  再次修改 Common/Object.php

   代碼如下:

  

  namespace Common;

  class Object{

  protected $array = array();

  function __set($key,$value){

  var_dump(__METHOD__);

  $this->array[$key] = $value;

  }

  function __get($key){

  var_dump(__METHOD__);

  return $this->array[$key];

  }

  }

  index.php

  代碼如下:

  

  define('BASEDIR',__DIR__); //定義根目錄常量

  include BASEDIR.'/Common/Loader.php';

  spl_autoload_register('CommonLoader::autoload');

  $obj = new CommonObject();

  $obj->title = 'hello';

  echo $obj->title;

  執行 index.php,頁面輸出:

  代碼如下:

  string 'CommonObject::__set' (length=20)

  string 'CommonObject::__get' (length=20)

  hello

  ② __call/__callStatic:控制 PHP 對象方法的調用(__callStatic 用來控制類的靜態方法)

  當執行一個不存在的php方法時

  index.php:

   代碼如下:

  

  define('BASEDIR',__DIR__); //定義根目錄常量

  include BASEDIR.'/Common/Loader.php';

  spl_autoload_register('CommonLoader::autoload');

  $obj = new CommonObject();

  //當執行一個不存在的php方法時

  $obj->test('hello',123);

  執行 index.php 會報一個致命錯誤:Fatal error: Call to undefined method CommonObject::test() in D:practisephpdesignpsr0index.php on line 9

  如果在 Common/Object 中定義一個__call 方法,則會在方法不存在時自動回調:

   代碼如下:

  

  namespace Common;

  class Object{

  function __call($func, $param){ //$func 方法名 $param 參數

  var_dump($func, $param);

  return "magic functionn"; //返回一個字符串作為返回值

  }

  }

  index.php

   代碼如下:

  

  define('BASEDIR',__DIR__); //定義根目錄常量

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 潼关县| 全椒县| 车致| 泽州县| 辽阳市| 安义县| 通道| 全州县| 额尔古纳市| 象山县| 临朐县| 荔浦县| 泰宁县| 法库县| 岳普湖县| 辽阳县| 嘉黎县| 珠海市| 永清县| 正定县| 兰溪市| 奎屯市| 嵊泗县| 平邑县| 平利县| 肃宁县| 大庆市| 上蔡县| 沐川县| 娄底市| 万盛区| 壤塘县| 无为县| 武乡县| 鄯善县| 宁都县| 章丘市| 竹溪县| 上蔡县| 云霄县| 丽水市|