PHP基礎(chǔ)之函數(shù)4——可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個變量名后有圓括號,PHP 將尋找與變量的值同名的函數(shù),并且嘗試執(zhí)行它。可變函數(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)用一個對象的方法。
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ù)調(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. Java GZip 基于內(nèi)存實現(xiàn)壓縮和解壓的方法2. idea配置jdk的操作方法3. SpringBoot+TestNG單元測試的實現(xiàn)4. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法5. python 浮點數(shù)四舍五入需要注意的地方6. Springboot 全局日期格式化處理的實現(xiàn)7. VMware中如何安裝Ubuntu8. Docker容器如何更新打包并上傳到阿里云9. 完美解決vue 中多個echarts圖表自適應(yīng)的問題10. JAMon(Java Application Monitor)備忘記
