PHP中return的用法

來源:互聯網
上載者:User

今天研究了一下CI架構的使用,注意到他的設定檔,採用一種寫法。如下:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.