Processing include/require directives in PHP

前端 未结 5 1364
广开言路
广开言路 2021-01-24 13:45

Background: I\'m building an automated test framework for a PHP application, and I need a way to efficiently \"stub out\" classes which encapsulate communicatio

5条回答
  •  时光说笑
    2021-01-24 14:16

    I've thought about this for a while now, and nobody has been able to point me to a clear and consistent explanation for the way PHP (up to 5.3 anyway) processes includes.

    I conclude that it would be better to avoid this issue entirely and achieve control over "test double" class substitution via autoloading:

    spl-autoload-register

    In other words, replace the includes at the top of each PHP file with a require_once() which "bootstraps" a class which defines the logic for autoloading. And when writing automated tests, "inject" alternative autoloading logic for the classes to be "mocked" at the top of each test script.

    It will naturally require a good deal of effort to modify existing code to follow this approach, but the effort appears to be worthwhile both to improve testability and to reduce the total number of lines in the codebase.

提交回复
热议问题