在不修改文件

时间:2016-03-10 15:08:09

标签: php class namespaces

我有一个第三方课,我需要修改其中一个方法。 我不想对第三方进行任何更改,所以我已经扩展了它。

class NewClass extends ThirdPartyClass {}

在我的代码和其他一些第三方类中使用了类名ThirdPartyClass,所以我希望保留该类名。

对此的解决方案是向类添加命名空间。

namespace thirdparty;

class ThirdPartyClass {}

然后扩展它

class ThirdPartyClass extends \thirdparty\ThirdPartyClass

但就像我说的那样,我不想对第三方类进行任何修改。

这个班是这样的。

require_once('thirdparty/3rdpartyclass.php');

我试过以下

namespace thirdparty;
require_once('thirdparty/3rdpartyclass.php');

namespace thirdparty;
include_once('thirdparty/3rdpartyclass.php');

有关如何为我的新班级使用相同班级名称的任何建议?

修改

这有效但与使用require_once

不同
eval('namespace thirdparty;?>' . file_get_contents('thirdparty/3rdpartyclass.php'));

这个问题与PHP namespace removal / mapping and rewriting identifiers无关,答案毫无帮助。

2 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但它没有实现require_once

eval('namespace thirdparty;?>' . file_get_contents('thirdparty/3rdpartyclass.php'));

class ThirdPartyClass extends \thirdparty\ThirdPartyClass {


}

答案 1 :(得分:0)

清洁,但没有解决方案

由于框架内部使用由命名空间和类名标识,因此无法在不更改原始类代码的情况下修改类方法。

唯一的解决方案 - 正如@mrun所提到的 - 是创建一个子类并覆盖您需要修改的方法。之后,您可以在项目代码中使用子类

肮脏的黑客

如果您使用自动加载器并可能影响其行为,则可以在非PSR兼容位置创建该类的副本并修改其代码。

通常,自动加载器获取作为参数传递的命名空间和类名,以包含文件系统中的匹配类文件。因此,如果自动加载器应该加载此类特殊类(包含类文件),则只需包含修改后的文件即可。

但是:如果框架更新,您必须确保您的修改版本仍然有效。

相关问题