IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

PHP中return的用法

Becomin' Charles 2012-12-04 00:00:55 累计浏览 5,486 次
本机暂存

   这两天,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 options in .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';

}

同分类推荐文章

  1. 美团 BI 在指标平台和分析引擎上的探索和实践 (2026-06-15 09:05:33)
  2. 把 Next.js 拆成壳:LobeHub 后端迁移 Hono 实录 (2026-06-10 19:27:40)
  3. 把 MinIO 示例迁到 OtterIO:使用、部署与迁移验证 (2026-06-09 22:34:00)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,207)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,108)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,362)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,084)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 12,741)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,484)
  7. Redis消息队列的若干实现方式 (累计阅读 12,023)
  8. 到底什么是MVC? (累计阅读 11,744)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 11,557)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,447)