有什么办法在PHP中安全地重新声明一个类吗? [英] Is there any way to redeclare a class safely in PHP?

查看:222
本文介绍了有什么办法在PHP中安全地重新声明一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道臭名昭着的不能redeclare类的错误。是否有任何方法来克服这个问题,并实际上声明一个具有相同名称的新类,或者这在PHP 5中是不可能的?

We all know the infamous "cannot redeclare class" error. Is there any method to overcome this and actually declare a new class with the same name, or is this impossible in PHP 5?

推荐答案

正如Pekka和Techpriester都指出:不,你不能。但是,如果您使用PHP> = 5.3,则可以使用命名空间和使用结构有效地重新命名类。下面是一个例子:

As Pekka and Techpriester both pointed out: no, you cannot. However, if you're using PHP >= 5.3, then you can use namespaces and the "use" construct to effectively "redeclare" the class. Here's an example:


// MyClass.php
class MyClass {
  const MY_CONST = 1;
}
// MyNamespaceMyClass.php namespace Mynamespace; class MyClass { const MY_CONST = 2; }
// example.php require_once 'MyClass.php'; require_once 'MyNamespaceMyClass.php';
use Mynamespace\MyClass as MyClass;
echo MyClass::MY_CONST; // outputs 2

因此,你得到了你想要的结果,是指您命名的类。

Thus, you've got your desired result, as MyClass now refers to your namespaced class.

这篇关于有什么办法在PHP中安全地重新声明一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆