PHP中return的用法


<?php

/**
* 注釋若干
* 以下是一個格式如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';
}
?>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM