Home > Mobile >  PHP equivalent for jQuery $.extend()?
PHP equivalent for jQuery $.extend()?

Time:12-31

Is there anything equivalent in PHP for jQuery's $.extend()?

I want to pragmatically merge/combine/extend classes with other classes and it's properties (including methods) without using late static binding.

class a {}
class b {}
class c {}

$merged = combine(new a(), new b(), new c());

This is not what I am looking for:

class a {}
class b extends a {}

$merged = new b();

CodePudding user response:

There isn't really anything equivalent in PHP, because their object systems are very different.

JavaScript doesn't have real classes like PHP does, its object system is based on prototypes. Methods can be direct properties of the instance, but if there isn't a direct property the prototype chain will be searched to find it. $.extend() automatically copies properties that are inherited from the prototype to the target object, so the result is kind of like an instance of a subclass of all the original classes.

But PHP doesn't have any equivalent to attaching methods directly to objects, so there's no way that a combine() function could merge all the methods from classes of the arguments. An object is an instance of a particular class, and it gets its methods from the class object (and its superclasses) only.

CodePudding user response:

Like @Barmar said, this isn't really a thing in PHP. Workarounds are ugly but I am going to describe two ugly workarounds for whoever want a big laugh.

  • Related