应该require_once"some file.php"; ;出现在文件顶部以外的任何位置? [英] Should require_once "some file.php" ; appear anywhere but the top of the file?

查看:80
本文介绍了应该require_once"some file.php"; ;出现在文件顶部以外的任何位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例是否适合PHP的require_once构造?

Is the following example appropriate for PHP's require_once construct?

function foo( $param )
{
    require_once "my_file.php" ;
    //
    // do something here
}

还是在文件的开头仅包含require_once构造更合适?

Or is it more appropriate to only have require_once constructs at the beginning of the file?

即使所包含的文件仅在该函数的上下文中才有用,但在顶部具有可读性和可维护性不是更好吗?

Even though the file being included is useful only in the context of the function, is it not better to have includes at the top for readability and maintainability?

推荐答案

这取决于编码风格和意见.就我个人而言,我所有的require_once语句都放在文件的最顶部,这样我就可以轻松地看到哪些文件包含在什么位置,没有什么更糟的了,而有些被埋没的文件会弄乱您的脚本.但是,如果您有几个仅某些功能所需的大型脚本,那么从性能的角度来看,将require_once放入功能中就可以了,只需确保在页面顶部添加注释即可.

It comes down to a matter of coding style and opinion. Personally I keep all my require_once statements at the very top of my files so I can easily see which files are included where, nothing worse then some buried include messing with your scripts. However, if you have several large required scripts that are only required for certain functions, then putting the require_once inside a function would be OK from a performance stand-point, just make sure to put a note at the top of the page.

<?php
//require_once "my_file.php" (see function foo)

function foo($param) {
  require_once "my_file.php";
}

这篇关于应该require_once"some file.php"; ;出现在文件顶部以外的任何位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆