As far as I know, there is not an easy way to overload a constructor in PHP in the same way as in C# or Java. There seems to be a whole bunch of different solutions or workarounds regarding this issue. I’ve been working a lot with PHP in my degree project and this is the technique we used to “overload” constructors.
You can create an array that contains your arguments and then check which parameters that are set in the array in the constructor. First you check the length of the parameter list and then which parameters that are declared. Then you set the class instance variables to the corresponding parameter value.
class Something
{
private $a;
private function SetA($a)
{
$this->a = $args['a'];
}
function __construct($args)
{
$numArgs = sizeof($args);
switch ($numArgs)
{
case 1:
if(isset($args['a']))
{
$this->SetA($args['a']);
}
break;
}
}
}
In whatever file that you need to create an object of the class above you can write the following code:
$args = array('a' => 'someValue');
$s = new Something($args);
The thing that I like the most with this technique with using an array in PHP is that you will most unlikely run out of a possibility to set whatever you want to set in your constructor. When you’re programming with C#, for example, it’s pretty easy to run out of constructors. Have you once declared a constructor that takes one string parameter you cannot overload that constructor with another constructor that also takes one string parameter.
Is there anyone who have another idea/tip on how to overload constructors using PHP?
Comments