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. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )2. asp文件用什么軟件編輯3. PHP基礎(chǔ)之生成器4——比較生成器和迭代器對(duì)象4. ASP新手必備的基礎(chǔ)知識(shí)5. Docker 啟動(dòng)Redis 并設(shè)置密碼的操作6. vue+element開(kāi)發(fā)一個(gè)谷歌插件的全過(guò)程7. Vue axios獲取token臨時(shí)令牌封裝案例8. JS中6個(gè)對(duì)象數(shù)組去重的方法9. 利用CSS制作3D動(dòng)畫10. Spring如何替換掉默認(rèn)common-logging.jar

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