PHP:'包含',但不要运行 [英] PHP: 'include', but don't run

查看:135
本文介绍了PHP:'包含',但不要运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个test.php,我运行单元测试用例。我想要的是'包含'某些.php文件,但是当我这样做时,它们就会运行。例如,我只需要从.php文件中访问某些变量,函数,但整个.php文件都会运行。就我而言,.php是一个巨大的文件。同样的事情发生在'require'

I have a test.php, where I run unit test cases. What I want is to 'include' certain .php files, but when I do it, they get run. For example, I just need to access certain variables, functions from a .php file, but the whole .php file gets run. In my case, the .php is a huge file. Same thing happening with 'require'.

是否可以访问那些.php方法,变量,函数没有运行它们?

Would it be possible to access those .php methods, variables, functions without running them?

谢谢!

推荐答案

这就是当代码包含在内,它作为整个脚本的一部分执行。你不会通过一些黑客解决这个问题,包括代码而不执行它。你可以通过将代码组织成可调用的单元来修复它。

That's what happens when code is included, it is executed as part of the overall script. You don't "fix this" by some hack which would include code without executing it. You fix it by organizing your code into invokable units.

事实上,单元测试是一种伟大的方式来开始考虑如何组织你的码。你究竟在测试什么?一类?一个功能?或者只是某个脚本中某些顶级代码的随机块?

In fact, unit testing is a great way to start thinking about how to organize your code. What exactly are you testing? A class? A function? Or just some random block of top-level code in a script somewhere?

如果是后者,您现在看到了问题。通过包含该代码,您可以执行它。这超出了正在运行的测试的上下文。相反,您希望该代码位于某种可调用的单元中。一个类,或者至少是一个函数。

If the latter, you are now seeing the problem. By including that code, you execute it. Which is outside the context of the test being run. Instead, you want that code to be in some invokable unit of some sort. A class, or at the very least a function.

例如,假设您有一个充满顶级代码的PHP文件,它执行各种任务。正如您所遇到的那样,当您包含该代码时,所有这些任务都会立即执行。但是,如果您将该文件中的代码组织成一组函数,那么通过包含它您正在做的就是定义函数。然后,使用代码(在这种情况下为单元测试)可以按照受控且可预测的方式按需执行这些功能。

For example, let's say you have a PHP file full of top-level code which performs a variety of tasks. As you are experiencing, when you include that code all of those tasks are immediately performed. However, if instead you organize the code in that file into a set of functions, then by including it all you're doing is defining the functions. Consuming code (the unit tests in this case) can then execute those functions as desired, in a controlled and predictable manner.

当您包含它时,所有代码都应该执行定义结构。然后顶级消费代码应该使用这些结构。将所有逻辑放入顶级代码使其无法实现且无法管理。

All the code should do when you include it is define the structures. Then the top-level consuming code should make use of those structures. Putting all logic into top-level code makes it untestable and unmanageable.

这篇关于PHP:'包含',但不要运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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