Can OOP programming be emulated with just normal functions? Like with using static variables and anonymous functions: http://php.net/manual/en/functions.anonymous.php
Can OOP programming be emulated with just normal functions? Like with using static variables
Share
OOP is about having a constructor function which initiates an object, accessible to other functions “statically” using the
thiskeyword.So yes, you can do OOP without using language constructs such as “class”, “this”, or __construct.
Normal OOP:
OOP using procedural language constructs (I have avoided the Object class to stay away from any OOP stuff, however it would be better to use it for the $self type, maybe to be able to use the -> accessor, or take advantage of automatic pass by reference):
Using PHP >=5.3 new anonymous function feature, you could add member functions as properties inside the $self array/object, more so because you can invoke directly (
$self["fill"]("abcde")). A nicer accesor is possible if using an object data type for $self.Depending on how you design your code, this procedural style OOP might be tweaked to work nicely in simple RPC scenarios (however, the constructor will never return a usable $self object/array, so you might as well go full OOP and have the same problem).
If going the (object)array() route, you can store the fill function in the object as a property, yet you will never have a
$thisreference (without passing it as param) or prototypal or any other kind of inheritance. You’d better stick with the class keyword in PHP, there’s no reason to go around it.If you also need inheritance, this is where it gets ugly: you need to create renamed functions for overriding, “type” conversion functions for the
$selfarray/object, etc.It can be done. If you have complex needs (like inheritance) it might get really ugly. If you have really simple needs, not so ugly, maybe even with advantages.