在 PHP 中是否有一些动态重写类的技巧?
我在两个不同的文件中有两个名为 test
的类,例如 a.php
和 b.php
,逻辑如下
include('a.php');
$a = new test();
if($somcondition_is_met)
{
include('b.php');
$b = new test();
}
:一些避免致命错误:无法重新声明类
的技巧?
I have two class named test
in two different files,a.php
and b.php
for instance,the logic is like this:
include('a.php');
$a = new test();
if($somcondition_is_met)
{
include('b.php');
$b = new test();
}
Is there some trick to avoid Fatal error: Cannot redeclare class
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
http://www.php.net/manual/en/language。命名空间.rationale.php
1)
http://www.php.net/manual/en/language.namespaces.rationale.php
1)
classkit_import() 看起来完全符合您的要求
http://www .php.net/manual/en/function.classkit-import.php
来自链接:
Example #1 classkit_import() example
newclass.php
main.php
上面的示例将输出:
噗!
酒吧!
classkit_import() looks like it does exactly what you want
http://www.php.net/manual/en/function.classkit-import.php
From the link:
Example #1 classkit_import() example
newclass.php
main.php
The above example will output:
foo!
bar!
对于“标准”PHP,不,你不能做这样的事情。
尽管如此,查看 PECL 和手册,可能会使用 classkit 扩展 -- 但它被标记为“未维护”,并且自 2004 年以来就没有更新过......所以我绝对不会使用它。
引用该扩展的 PECL 页面:
那么,让我们看一下 runkit 扩展,它可能会执行以下操作:技巧——尤其是
runkit_import
函数可能会让您感兴趣(引用):不过,请注意,官方(查看它的PECL 页面) ,runkit 扩展自 2006 年以来就没有更新过...这也不是一个好兆头...特别是当涉及到 PHP 5.3 支持时...
With "standard" PHP, no, you cannot do such a thing.
Still, looking at PECL and the manual, a possibility would be to use the classkit extension -- but it's marked as "not maintained", and has not been updated since 2004... So I would definitly not use it.
Quoting the PECL's page of that extension :
So, let's take a look at the runkit extension, which might do the trick -- especially, the
runkit_import
function could interest you (quoting) :Still, note that, officially (looking at it's PECL page), the runkit extension has not been updated since 2006... Which is not a good sign either... Especially when it comes to PHP 5.3 support...
我认为最好使用接口,而不是动态覆盖类。
在您的代码中,您引用/使用接口类,并且您可以有多个实现该接口的类。
检查文档以获取有关接口的更多详细信息。
http://php.net/manual/en/language.oop5.interfaces。 php
I think it is better to use Interfaces, rather then overwriting classes dynamicaly.
In your code you reference/use the interface class, and than you can have multiple classes that implement that interface.
Check the doc for more details on interfaces.
http://php.net/manual/en/language.oop5.interfaces.php