Obviously we cannot do this in PHP, and why would we, right? However we can emulate this behaviour to a certain extent using my “neat” little Prototype class. With this Prototype class we can dynamically add properties and methods to any class, and they will be inherited by all instances of that class. Let’s look at the following “normal” PHP code.
Now, there is nothing magical or out-of-the-ordinary going on here. We just instantiate the Person
class and setup some properties. Calling the
outputs a nice little string for us.
However, you see that the Person class is actually a child of the Prototype class. This will allow
$age property and an
age() method to output a nice string. Like so:
Now all instances of Person inherit the
$age property and
age() method. So we can create a new
Person, Susie, and this object will now have the age stuff.
One limitation of the Prototype class though, is you cannot overload a current method. So the
following code, that attempts to overload the
will not work.
There are also many, many, many other problems with this Prototype class. Some of which are:
- The ‘$this’ keyword is reserved, so it actually does a string replace and uses ‘$self’ instead.
- You cannot access/add new methods or properties statically (until PHP 5.3 with
- It uses
create_function, so every “method” is actually defined in the global namespace.
- Iteration does not work, although it could possibly be done with Iterator, Countable, et al.
- You cannot reference static variables/methods in your add method.
- You cannot share methods between classes.
- And so on and so forth…