Menu

PHP 中 return 的特別用法

這兩天,Charles研究Yii框架的使用,注意到Yii的配置文件,採用一種寫法。如下:

  /**
* 註釋若干
* 以下是一個格式如config.php的文件
*/

return array(
'config1' => 'some value',
'config2' => 'some value',
);
?>

在這個文件中,直接就寫了一個return,這個用法又一次突破了我的常識。特意查詢了一下文檔,裡面這樣描述的:

return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

return語句可以終止函數執行那自不必說了,這裡還提到了可以終止eval過程的進行,並且如果處於被include的文件中,還能使return的值成為include和require函數的返回值。這樣寫的好處是,一個語句就可以得到配置項的內容了。

  //原來這樣寫
require './config.php';
function test() {
global $config;
if ($config['a']=='b') echo 'hello';
}

//現在
function test() {
$config = require('./config.php');
if ($config['a']=='b') echo 'hello';
}
?>

作者:Charles

原文鏈接:[Tips] PHP中return的用法