PHP基礎(chǔ)之函數(shù)4——可變函數(shù)
PHP 支持可變函數(shù)的概念。這意味著如果一個(gè)變量名后有圓括號(hào),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è)對(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. 使用css實(shí)現(xiàn)全兼容tooltip提示框2. 關(guān)于Mysql-connector-java驅(qū)動(dòng)版本問題總結(jié)3. 使用ProcessBuilder調(diào)用外部命令,并返回大量結(jié)果4. 通過工廠模式返回Spring Bean方法解析5. JSP實(shí)現(xiàn)客戶信息管理系統(tǒng)6. python:刪除離群值操作(每一行為一類數(shù)據(jù))7. python中HTMLParser模塊知識(shí)點(diǎn)總結(jié)8. CSS自定義滾動(dòng)條樣式案例詳解9. python 批量下載bilibili視頻的gui程序10. Ajax提交post請(qǐng)求案例分析
