可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號(hào),PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。可變函數(shù)可以用來(lái)實(shí)現(xiàn)包括回調(diào)函數(shù),函數(shù)表在內(nèi)的一些用途。
變量函數(shù)不能用于語(yǔ)言結(jié)構(gòu),例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及類(lèi)似的語(yǔ)句。需要使用自己的包裝函數(shù)來(lái)將這些結(jié)構(gòu)用作變量函數(shù)。
先將我的偽代碼寫(xiě)上。
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 就是分頁(yè)。寫(xiě)完以后覺(jué)得哪里不對(duì)。在我們平常的寫(xiě)法中,查找全部數(shù)據(jù) $this->model->orderBy($order, $sort)->get();
是這樣的,我也未見(jiàn)過(guò)使用變量來(lái)替換 get() 的。在實(shí)際運(yùn)行中,程序正常執(zhí)行。隨后在論壇中詢(xún)問(wèn)這種寫(xiě)法。接下來(lái)就要引入一個(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í)行。
示例:
?php function foo() { echo "In foo()br />\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.br />\n"; } $func = 'foo'; $func(); // 執(zhí)行 foo(); 命令行中輸出:In foo()br /> $func = 'bar'; $func('test'); // 執(zhí)行 bar();命令行中輸出:In bar(); argument was 'test'.br />
可變函數(shù)的語(yǔ)法來(lái)調(diào)用一個(gè)對(duì)象的方法。
?phpclass Foo { function Variable() { $name = 'Bar'; $this->$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)屬性?xún)?yōu)先。Variable 方法和靜態(tài)屬性示例。
?php class Foo { static $variable = 'static property'; static function Variable() { echo 'Method Variable called'; } } echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope. $variable = "Variable"; Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope.
總結(jié)
以上所述是小編給大家介紹的php 可變函數(shù)使用小結(jié),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
標(biāo)簽:泰州 山東 梅州 巴中 成都 林芝 威海 張家口
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php 可變函數(shù)使用小結(jié)》,本文關(guān)鍵詞 php,可變,函數(shù),使用,小結(jié),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。