阻止 PHP require_once 运行
调试别人的 PHP 代码时,我想有选择地重写他们的一个类。该类通过以下方式包含:
require_once('classname.php');
但是,它出现在应用程序的各个位置。我宁愿“模拟”require_once,这样它就永远不会运行。即按照我的需要定义class classname
。然后,下次文件被 require_once
编辑时,它会被标记为已加载,因此不会重新加载。
我可以创建自己的 classname.php 文件,但我宁愿将我正在执行的测试包含在单个文件中,因为我可能为许多类执行此操作,并且我希望更轻松地控制压倒一切。
在 Perl 中,我想做的是:
$INC{'classname.pm'} = 1;
有没有办法访问 PHP 的 Perl 的 %INC
等价物?
更新:一直对 PHP 不允许你做的事情感到惊讶......
我的解决方法是使用 runkit 的 runkit_method_redefine
。我加载我试图阻止加载的类,然后重新定义我试图“模拟”的所有方法,例如:
require_once('classname.php');
runkit_method_redefine('classname','method','$params','return "testdata";');
Debugging someone else's PHP code, I'd like to selectively override one of their classes. The class is included via:
require_once('classname.php');
But, that appears in various places in the application. I'd rather 'simulate' the require_once
, so that it never gets run at all. I.e. just define class classname
as I want it. Then, the next time the file was require_once
'ed, it'd be flagged as already-loaded and thus not reloaded.
I can create a classname.php file of my own, but I'd rather keep the testing I'm doing contained to a single file, as I'm doing this possibly for many classes, and I'd like easier control over the overriding.
In Perl, what I'd want to do would be:
$INC{'classname.pm'} = 1;
Is there a way to access PHP's equivalent of Perl's %INC
?
Update: Consistently surprised by what PHP doesn't let you do...
My workaround was to use runkit's runkit_method_redefine
. I load the classes I was trying to prevent loading, and then redefine all the methods I was trying to 'mock', e.g.:
require_once('classname.php');
runkit_method_redefine('classname','method','$params','return "testdata";');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
位置:
位于
classname.php
文件的最顶部。Place:
at the very top of
classname.php
file.require_once 会为你做到这一点..
另外你可以使用一些像 hacky 这样的东西
require_once does this for you..
Additionally you could use something hacky like
我在想你的意思是,代码中的其他地方完全有可能存在另一个“required_once”,这会导致你的代码被覆盖。
您可以做两件事:
1)找到第一个“必需”,然后将其注释掉。
2)进入类文件并包含您的类并在定义其他类之前返回。
I'm thinking what you mean is that it's entirely possible that there is another "required_once" somewhere else in the code that would cause yours to be overwritten.
There are two things you can do:
1) Hunt down the first "required" and then comment it out.
2) Go into the class file and include your class and return before the other class is defined.