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

首頁 > 語言 > PHP > 正文

php 可變函數使用小結

2024-09-04 11:49:33
字體:
來源:轉載
供稿:網友

可變函數

PHP 支持可變函數的概念。這意味著如果一個變量名后有圓括號,PHP 將尋找與變量的值同名的函數,并且嘗試執行它。可變函數可以用來實現包括回調函數,函數表在內的一些用途。

變量函數不能用于語言結構,例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及類似的語句。需要使用自己的包裝函數來將這些結構用作變量函數。

先將我的偽代碼寫上。

  1. protected $model
  2. public function __construct(Category $category
  3.  $this->model = $category
  4. public function getLists($request$isPage = 'get'$order = 'created_at'$sort = 'desc'
  5.  return $this->model->orderBy($order$sort)->$isPage(); 

在 getLists 中,有一個 $isPage 的參數。本意是傳入 get 就是獲取全部數據,paginate 就是分頁。寫完以后覺得哪里不對。在我們平常的寫法中,查找全部數據 $this->model->orderBy($order, $sort)->get(); 是這樣的,我也未見過使用變量來替換 get() 的。在實際運行中,程序正常執行。隨后在論壇中詢問這種寫法。接下來就要引入一個概念,《可變函數》。

什么是可變函數?

PHP 支持可變函數的概念。這意味著如果一個變量名后有圓括號,PHP 將尋找與變量的值同名的函數,并且嘗試執行它。

了解了這個概念以后那么上述程序就可以講的通了。$isPage 在程序運行中,替換為 get, 而 $isPage 后有一個圓括號,那么程序就會尋找同名函數。進而繼續執行。

示例:

  1. <!--?php 
  2. function foo() { 
  3.  echo "In foo()<br /-->/n"
  4. function bar($arg = '') { 
  5.  echo "In bar(); argument was '$arg'.<br>/n"
  6. $func = 'foo'
  7. $func();  // 執行 foo(); 命令行中輸出:In foo()<br> 
  8. $func = 'bar'
  9. $func('test'); // 執行 bar();命令行中輸出:In bar(); argument was 'test'.<br> 

可變函數的語法來調用一個對象的方法。

  1. <!--?phpclass Foo 
  2.  function Variable() 
  3.  { 
  4.   $name = 'Bar'
  5.   $this--->$name(); // This calls the Bar() method 
  6.  } 
  7.  function Bar() 
  8.  { 
  9.   echo "This is Bar"
  10.  } 
  11. $foo = new Foo(); 
  12. $funcname = "Variable"
  13. $foo->$funcname(); // This calls $foo->Variable() 
  14. // 命令行執行輸出: This is Bar 

當調用靜態方法時,函數調用要比靜態屬性優先。Variable 方法和靜態屬性示例。

  1. <!--?php 
  2. class Foo 
  3.  static $variable = 'static property'
  4.  static function Variable() 
  5.  { 
  6.   echo 'Method Variable called'
  7.  } //Vevb.com 
  8. echo Foo::$variable// This prints 'static property'. It does need a $variable in this scope. 
  9. $variable = "Variable"
  10. Foo::$variable(); // This calls $foo--->Variable() reading $variable in this scope. 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武乡县| 南京市| 登封市| 涪陵区| 彭泽县| 纳雍县| 慈利县| 睢宁县| 新泰市| 苏尼特右旗| 江津市| 罗平县| 波密县| 海淀区| SHOW| 泽州县| 忻城县| 延庆县| 唐河县| 富裕县| 山阳县| 高安市| 平泉县| 杂多县| 舒城县| 普宁市| 福海县| 通河县| 马鞍山市| 定边县| 乌拉特中旗| 大埔县| 娱乐| 特克斯县| 山东省| 策勒县| 鹤壁市| 芒康县| 长治市| 萝北县| 玉田县|