PHP基礎(chǔ)之函數(shù)4——可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號,PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。可變函數(shù)可以用來實(shí)現(xiàn)包括回調(diào)函數(shù),函數(shù)表在內(nèi)的一些用途。
可變函數(shù)不能用于例如?echo,?print,?unset(),?isset(),?empty(),?include,?require?以及類似的語言結(jié)構(gòu)。需要使用自己的包裝函數(shù)來將這些結(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ù)的語法來調(diào)用一個(gè)對象的方法。
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. Android如何加載Base64編碼格式圖片2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 解決Android studio xml界面無法預(yù)覽問題4. 基于android studio的layout的xml文件的創(chuàng)建方式5. 圖文詳解vue中proto文件的函數(shù)調(diào)用6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)7. 什么是python的自省8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備