问题
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();
回答1:
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 :)
来源:https://stackoverflow.com/questions/2192049/prototypal-inheritance-in-php-like-in-javascript