there is a project which I need to extend. All classes are in seperate files, I need to extend some of the classes without rewriting existing code in other files. My idea was to use namespaces but I fail. Here is an example:
I've renamed the original A.php class file to A_Original.php:
class A
{
public function hello()
{
echo "hello world from Class A\n";
}
}
Then created a new A.php:
namespace AOriginal {
include 'A_Original.php';
}
namespace {
class A
{
public function hello()
{
echo "hello world from Class A Extended\n";
}
}
}
This fails because on including
the original A_Original.php file the class is dumped to the global scope (thus ignoring the namespace command).
I can not modify the existing code inthe A_Original.php file, but renaming is ok.
The other project files (whic I cannot modify) use a require "A.php"
.
How to accomplish this?
To address this problem, namespaces were introduced in PHP as of PHP 5.3. The best way to understand namespaces is by analogy to the directory structure concept in a filesystem. The directory which is used to group related files serves the purpose of a namespace.
A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.
Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
You can extend a class without modifying its existing behaviour:
class A {
public function foo(){
}
}
class MySubClassOfA extends A {
public function bar(){
}
}
You can add your own methods to MySubClassOfA, i.e. bar(). You can call the foo method on MySubClassOfA and it's behaviour is the same, unless you define a method called foo in MySubClassOfA.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With