本文介绍了是具有“副作用"的include()/require()吗?不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在做类似的事情

_________________________
//index.php
...
require("header.php");
...
_________________________

_________________________
//header.php
printHeader()

function printHeader(){
    echo 'something';
    ...
}
_________________________

考虑过要避免的不良习惯?

我个人认为,执行require()(或require_once()include(),这不是重点)的调用应仅向其他函数/对象添加链接",而决不要自己执行任何操作.换句话说,我认为需求的行为与其他oo语言的导入/使用非常相似.

我上面编写的示例相当简单,但显然我也在针对各种副作用"进行编写.我经常在某些包含的文件中发现定义功能或会话技巧,这是我经常发现的其他弊端.

解决方案

是的,恕我直言,这是非常不好的做法,除非非常明确地记录下来.

includerequire(以及其他语言的等效语言)通常仅将引入新功能到当前作用域中,并且永远不要触发它们的调用.

Is doing something like

_________________________
//index.php
...
require("header.php");
...
_________________________

_________________________
//header.php
printHeader()

function printHeader(){
    echo 'something';
    ...
}
_________________________

considered a bad practice to avoid?

I personally believe that the execution of a require() (or require_once() or include(), that's not the point) call should only add a "link" to other functions/objects and never execute anything on its own. In other words in my opinion a require should behave in a very similar way to the import/using of other oo languages.

The example that I've written above is pretty trivial but obviously I'm writing also against every kind of "side effects". The define function or some tricks with sessions are other abuses that I have found often in some included files.

解决方案

Yes, IMHO it's (very) bad practice unless very explicitly documented.

include or require (and their equivalents in other languages) should normally only introduce new functions into the current scope, and never trigger their invocation.

这篇关于是具有“副作用"的include()/require()吗?不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:44