Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototypal inheritance in PHP (like in JavaScript)

Is it possible to employ some kind of prototypal inheritance in PHP like it is implemented in JavaScript?

This question came to my mind just out of curiosity, not that I have to implement such thing and go against classical inheritance. It just feels like a interesting area to explore.

Are there prebuild functions to combine classical inheritance model in PHP with some sort of Prototypal inheritance with a combination of anonymous functions?

Let's 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();
like image 981
Juraj Blahunka Avatar asked Feb 03 '10 13:02

Juraj Blahunka


People also ask

How prototypal inheritance is different from classical inheritance in JavaScript?

Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.

What is prototypal inheritance JavaScript?

Simply put, prototypical inheritance refers to the ability to access object properties from another object. We use a JavaScript prototype to add new properties and methods to an existing object constructor. We can then essentially tell our JS code to inherit properties from a prototype.

What languages use prototypal inheritance?

Prototypal inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical.

What is prototypal inheritance give example?

Here we can say that " animal is the prototype of rabbit " or " rabbit prototypically inherits from animal ". So if animal has a lot of useful properties and methods, then they become automatically available in rabbit . Such properties are called “inherited”.


1 Answers

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

If you are looking to have something like mixins/traits, you could use Decorators.

There is an RFC about whether to have traits in PHP6 though.

What you could do, is have Prototype pattern that tracks the lifecycle of it's cloned objects through an SplObjectStorage. Whenever the prototype is changed, the Builder would walk through the map and adjust the instances accordingly. Monkey patching would have to be done through runkit though. Doesn't sound too feasible imho :)

like image 190
Gordon Avatar answered Oct 13 '22 00:10

Gordon