Is there any way to redeclare a class safely in PH

2019-04-06 12:04发布

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?

标签: php oop class
7条回答
别忘想泡老子
2楼-- · 2019-04-06 13:05

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.

查看更多
登录 后发表回答