【发布时间】:2016-06-25 12:26:31
【问题描述】:
我有一个第 3 方类,我需要修改它的一种方法。 我不想对第 3 方进行任何更改,所以我已经扩展了它。
class NewClass extends ThirdPartyClass {}
类名 ThirdPartyClass 在我的代码和其他一些第 3 方类中使用,所以我想保留该类名。
解决方案是为类添加命名空间。
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 无关,答案毫无帮助。
【问题讨论】:
-
您希望使用
ThirdPartyClass类的第 3 方使用您的修改版本还是继续使用“原始”类? -
@mrun,它只是我的代码需要使用修改后的版本,但如果第三方更容易使用修改后的类,那很好。
-
@TarranJones 我可能在这里遗漏了一些东西(如果是这种情况,请原谅我!)但是是什么阻止了你以任何你想要的方式命名你的类,只修改 你的使用该名称的代码?
-
@mron 抱歉,我之前错了。我无法编辑的代码需要使用
ThirdPartyClass的修改版本。我将框架本身作为“我的代码”包含在内,并且我希望对核心进行最小的更改。
标签: php class namespaces