Rishav Rastogi Rishav Rastogi - 1 month ago 17
PHP Question

Concept of Modules in php similar to Ruby

Is there something similar to the ruby module construct in php ?

Basically I need to create a modules for a mix-in b/w different classes etc.

I know that php has the concept of mixins b/w different classes, but not sure about modules.

Answer

PHP doesn't have mixins in the same way Ruby has them. That is, you can't change anything about a class after it's been defined, and you can't sanely add new methods to an instance after it's been created 1. PHP only has the plain old vanilla single-inheritance mechanism, interfaces, and composing traits in 5.4.

The closest thing that PHP might have to a Ruby module is going to be a class. The closest thing that PHP might have to a Ruby mixin is a trait, but traits are not dynamic. They must be referenced by any implementing class at the time that the class is defined. They can not be added or modified at runtime, and apply to the class as a whole, not to individual instances.

While PHP 5.3 has namespaces, they are restricted to holding functions, classes, constants, traits and interfaces only, meaning you can't define variables as a first-class member of a namespace. Attempting to do so results in them being defined in the root namespace instead, which is certainly not what anybody would want. Further, there is no namespace inheritance mechanism, only a namespace reference mechanism.

1: While you can add instance variables (properties) after an object has been created by simply referencing them, this is considered a bad practice. Properties can also contain anonymous functions, but abusing properties this way to emulate adding methods is also bad practice.