本篇文章為大家展示了可變函數(shù)怎么在php中使用,內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號(hào),PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。可變函數(shù)可以用來實(shí)現(xiàn)包括回調(diào)函數(shù),函數(shù)表在內(nèi)的一些用途。
變量函數(shù)不能用于語言結(jié)構(gòu),例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及類似的語句。需要使用自己的包裝函數(shù)來將這些結(jié)構(gòu)用作變量函數(shù)。
先將我的偽代碼寫上。
protected $model; public function __construct(Category $category) { $this->model = $category; } public function getLists($request, $isPage = 'get', $order = 'created_at', $sort = 'desc') { return $this->model->orderBy($order, $sort)->$isPage(); }
在 getLists 中,有一個(gè) $isPage 的參數(shù)。本意是傳入 get 就是獲取全部數(shù)據(jù),paginate 就是分頁。寫完以后覺得哪里不對(duì)。在我們平常的寫法中,查找全部數(shù)據(jù)$this->model->orderBy($order, $sort)->get();
是這樣的,我也未見過使用變量來替換 get() 的。在實(shí)際運(yùn)行中,程序正常執(zhí)行。隨后在論壇中詢問這種寫法。接下來就要引入一個(gè)概念,《可變函數(shù)》。
什么是可變函數(shù)?
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號(hào),PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。
了解了這個(gè)概念以后那么上述程序就可以講的通了。$isPage 在程序運(yùn)行中,替換為 get, 而 $isPage 后有一個(gè)圓括號(hào),那么程序就會(huì)尋找同名函數(shù)。進(jìn)而繼續(xù)執(zhí)行。
示例:
\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.
\n"; } $func = 'foo'; $func(); // 執(zhí)行 foo(); 命令行中輸出:In foo()
$func = 'bar'; $func('test'); // 執(zhí)行 bar();命令行中輸出:In bar(); argument was 'test'.
可變函數(shù)的語法來調(diào)用一個(gè)對(duì)象的方法。
$name(); // This calls the Bar() method } function Bar() { echo "This is Bar"; } } $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable() // 命令行執(zhí)行輸出: This is Bar
當(dāng)調(diào)用靜態(tài)方法時(shí),函數(shù)調(diào)用要比靜態(tài)屬性優(yōu)先。Variable 方法和靜態(tài)屬性示例。
Variable() reading $variable in this scope.
上述內(nèi)容就是可變函數(shù)怎么在php中使用,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。