Prototype inheritance in PHP (e.g. in JavaScript)

Is it possible to use some prototype inheritance in PHP , as it is implemented in JavaScript ?

This question came to my mind only out of curiosity, and not that I should realize such a thing and go against classical inheritance. This is just an interesting area to explore.

Are there prebuild functions for combining the classic inheritance model in PHP with some kind of Prototypal inheritance with a combination of anonymous functions?

Say I have a simple class for UserModel

class UserModel implements PrototypalInheritance { // setters, getters, logic.. static public function Prototype () {} } $user = new UserModel(); UserModel::prototype()->getNameSlug = function () { return slugify($this->getUserName()); } echo $user->getNameSlug(); 
+6
javascript inheritance prototype php prototypal-inheritance
source share
1 answer

You can use the Prototype Creational Pattern to achieve something similar to this, but real prototypical inheritance like that found in JavaScript is not possible. afaik.

If you are looking for something like mixins / traits, you can use Decorators .

There is an RFC on whether it has traits in PHP6 .

What you can do is a Prototype template that tracks the life cycle of its cloned objects via SplObjectStorage. Whenever a prototype changes, the Builder will go through the map and adjust the instances accordingly. The monkey patch would have to be run through the runkit . Doesn't sound too doable imho :)

+2
source share

All Articles