PHP Multiple Signatures in Class Constructors

Posted on Posted in PHP

Ok, I wanted to share what I have been working on as usual and two different ways I have come across kind of implementing multiple constructor methods within one class.

One way is to take the data coming into the constructor and delegating to private methods for initialization based on the type that comes in.

Example:

public function __construct($data) {
    if(filter_var($data, FILTER_VALIDATE_INT)) {
        // Do something here
    }

    if(is_array($data)) {
        // Do something different here.
    }
}

This works great if you are always expecting only one variable to be passed into your constructor, say a record id or data array. But what if you want multiple variables into your constructor and you want to enforce some data integrity with type casting or something. What if the constructor can take on multiple different objects.

Well, I came across something akin to the singleton but instead you instantiate your objects with static methods. So for example:

public function __construct() {
   // Do some generic stuff here
}

public static function with2Arguments($arg1, $arg2) {
    $instance = new self();

    $instance->getWith2Arguments($arg1, $arg2);

    return $instance;
}

private function getWith2Arguments($arg1, $arg2) {
    // Do some initialization work here
}

public static function withArray(array $data) {
    $instance = new self();

    $instance->fill($data);

    return $instance;
}

Now, this can get complicated but this is a fairly decent alternative in my mind to creating multiple signatures for object instantiation. And it’s not new or unheard of. There are also other more complicated patterns that are more easily extendable but for smaller projects that aren’t going to be consumed by outside developers, this works great. (Think self-contained micro-application for the Internet.)