freediver
freediver

Reputation: 309

How to protect a class in PHP

We work on a PHP project which has plugins. Our plugin includes one open source class.

Another plugin uses this same class.

PHP will throw "Can not re-declare class" error if both plugins include a same class.

We can not to ask if class_exists because we want to use our class file as the other plugin might use an older or newer version.

We also do not want to rename the class as we want to keep the class file easily upgradeable to a newer version later.

We can't change the other plugin so is there anything we can do when including this file to avoid the error?

Upvotes: 4

Views: 188

Answers (4)

symcbean
symcbean

Reputation: 48357

Use require_once() rather than include() (or use the autoloader)

Upvotes: 0

Jaison Justus
Jaison Justus

Reputation: 2793

check the second answer of this question . i think that will be the issue PHP Fatal error: Cannot redeclare class. hope it will help.

have a nice day...

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75609

The best solution would be to put the two classes in different namespaces, but this is only supported from PHP 5.3.

Upvotes: 3

Related Questions