So I need to include modular code/libraries in my project, a new library:
Library A:
a.php: class A;
Library B: (with v1.0 checked out from A)
b.php: include_once a.php; class B extends A;
Library C: (with v2.0 checked out from A)
c.php: include_once a.php; class C extends A;
Library D:
d.php: include_once b.php,c.php;
This obviously leads to name conflict (cannot redeclare A
).
I cannot touch either of the libraries as they are frequently pulled from elsewhere. Also, I need the result to be another library, so nested namespaces is not an option. But I guess there must be plenty of other projects with the same problem?? Thanks for any suggestions.
You can use require_once or include_once, in place of your include
s.
These may affect performance, as memory and processing has to be used to keep track of included classes and check against it, but it's the easiest solution. How much they do, depends on how many include/require_once are in your single page load.
More complicated ones would implement a class autoloader, but you might not want to go there...
EDIT--
If I understand well your problem, it's a dependency problem. Libraries B and C both refer to A, but each refers to a different version of A. If that's the case, the solution is not trivial: any use of require_once or include_once will lead to undetermined first loaded version of A to be used. Any use of include will result in class duplication. I don't think you can solve the issue by just using these functions. What you'd need to do would be to manage library dependencies.
For example, an autoloader that recognises several versions of a class library and loads the most recent one (this assuming that you keep backwards compatibility across versions). You could also try to use nested classes, to keep each library's dependencies isolated and self-contained.
You can check if a class got declared already, in case your filenames are different for each version. Example:
if (!class_exists('A')) {
include a-XX.php;
}
Note that this way you only load one version of your class.
If I understand you well
your problem is that
Library B And C includes the same file which is A
And you want B And C In D in the other B and C which has the same file which is A so it shows
Fatal error: Cannot redeclare class A in
ok ---> in files c.php , b.php And d.php include_once 'a.php'
; OR require_once 'a.php'
;