Discuz教程网

PHP中return的用法

[复制链接]
authicon dly 发表于 2012-2-16 13:42:58 | 显示全部楼层 |阅读模式
这两天,Charles研究Yii框架的使用,注意到Yii的配置文件,采用一种写法。如下:


  1. /**
  2. * 注释若干
  3. * 以下是一个格式如config.php的文件
  4. */

  5. return array(
  6. 'config1' => 'some value',
  7. 'config2' => 'some value',
  8. );
  9. ?>
复制代码

在这个文件中,直接就写了一个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函数的返回值。这样写的好处是,一个语句就可以得到配置项的内容了。
  1. //原来这样写
  2. require './config.php';
  3. function test() {
  4. global $config;
  5. if ($config['a']=='b') echo 'hello';
  6. }

  7. //现在
  8. function test() {
  9. $config = require('./config.php');
  10. if ($config['a']=='b') echo 'hello';
  11. }
  12. ?>
复制代码




上一篇:6kuku.com申请免费空间
下一篇:callke.com 请求申请免费空间
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 05:26

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表