PHP基礎(chǔ)之函數(shù)4——可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號(hào),PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。可變函數(shù)可以用來(lái)實(shí)現(xiàn)包括回調(diào)函數(shù),函數(shù)表在內(nèi)的一些用途。
可變函數(shù)不能用于例如?echo,?print,?unset(),?isset(),?empty(),?include,?require?以及類似的語(yǔ)言結(jié)構(gòu)。需要使用自己的包裝函數(shù)來(lái)將這些結(jié)構(gòu)用作可變函數(shù)。
Example #1 可變函數(shù)示例
<?phpfunction foo() { echo 'In foo()<br />n';}function bar($arg = ’’) { echo 'In bar(); argument was ’$arg’.<br />n';}// 使用 echo 的包裝函數(shù)function echoit($string){ echo $string;}$func = ’foo’;$func(); // This calls foo()$func = ’bar’;$func(’test’); // This calls bar()$func = ’echoit’;$func(’test’); // This calls echoit()?>
也可以用可變函數(shù)的語(yǔ)法來(lái)調(diào)用一個(gè)對(duì)象的方法。
Example #2 可變方法范例
<?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()?>
當(dāng)調(diào)用靜態(tài)方法時(shí),函數(shù)調(diào)用要比靜態(tài)屬性優(yōu)先:
Example #3 Variable 方法和靜態(tài)屬性示例
<?phpclass 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.?>
相關(guān)文章:
1. el-input無(wú)法輸入的問(wèn)題和表單驗(yàn)證失敗問(wèn)題解決2. vue跳轉(zhuǎn)頁(yè)面常用的幾種方法匯總3. react腳手架配置代理的實(shí)現(xiàn)4. JavaScript中顏色模型的基礎(chǔ)知識(shí)與應(yīng)用詳解5. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂(lè)代碼6. JavaScript快速實(shí)現(xiàn)一個(gè)顏色選擇器7. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)8. 不要在HTML中濫用div9. Jquery使用原生AJAX方法請(qǐng)求數(shù)據(jù)10. React實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)hook組件實(shí)戰(zhàn)示例
