phpinclude

PHP: 'include', but don't run


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'.

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

Thanks!


Solution

  • 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.

    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.