I have a base class that I want to be able to extend by adding ‘modules’ to it. I can think of a few ways to do this:
each module extends the base class. If the base class contains a large amount of data, then instantiating many modules, all extending the base class, seems like it would be a waste of memory when the base class could instead just be instantiated once and then shared amongst the modules.
each module takes a reference to an object of the base class as a parameter, so it can access the base class’ methods and properties (which would all need to be made public).
the base class takes a parameter of all the modules, so it can access the modules’ methods and properties (which would all need to be made public).
I would write a base class with properties and methods that would be common to all the objects it represents and then extensions for objects of a particular type.
For example you can have a base class for a form validator that validates common form elements like username, password, email address etc etc and then an extension for a particular application where form data might include a product_id, product_name etc etc
This is inheritance vs. composition. In general, you should try to use composition (The last of those two approaches) over inheritance. It’s much more flexible and it keeps coupling down in your application. There are cases where inheritance may be a better choice, but if you need a rule-of-thumb, always go with composition.
This is a general problem and without more specific details, the correct approach can’t really be found. Only with specific problems can the right methods be constructed.
I’d almost always use your second approach, which is called encapsulation. The reason being that with inheritance as described in post#2, a child class extending a parent always extends that parent. This is where polymorphism comes in…
Ok imagine classes A and B (imaginative, I know!). A and B perform similar roles but are not exactly the same, and both implement an iParent interface.
<?php
interface iParent{
public function output();
}
class A implements iParent{
public function output(){
echo "Hello, I am class A";
}
}
class B implements iParent{
public function output(){
echo "Hello, I am class B";
}
}
You want a child class C, which can have either parent. If you used inheritance, you would need 2 classes here, C_A and C_B (where C_x extends x):
class C_A extends A{
}
class C_B extends B{
}
If you used encapsulation such a thing is not required:
class C{
function __Construct(iParent $Parent = null){
if($Parent == null){
$Parent = getDefault('iParent'); //or whatever autoloading mechanism you choose
}
echo 'This is my parent: "';
$this->Parent->Output();
echo '"';
}
}
The actual workings of class C can be modified by simply changing the parameter to it’s __Construct function. This isn’t the case with inheritance.