read

As you probably know, it’s possible to have multiple constructors in Java. They need to have the same name as the class, and they can only be distinguished by the number and type of arguments. In PHP5, you can only have one constructor. You can define it using the reserved word __construct. If the __construct function doesn’t exist, PHP5 will search for the old-style constructor function (by the name of the class). So if we cannot have multiple constructors, how could we create objects with different initial conditions? It’s not a big deal. There’s a pattern called Factory Method, which defines virtual constructors using static methods. Let’s see an example:

class Person
 {
     private $name;
     private $email;

     public static function withName($name)
     {
         $person       = new Person();
         $person->name = $name;

         return $person;
     }

     public static function withEmail($email)
     {
         $person        = new Person();
         $person->email = $email;

         return $person;
     }

     public static function fullPerson($name, $email)
     {
         $person        = new Person();
         $person->name  = $name;
         $person->email = $email;

         return $person;
    }
 }

We have a class called Person which contains 2 private attributes: name and email. It also has 3 static methods: withName, withEmail and fullPerson. These methods will behave like constructors.

So if we want to create a Person object just with the name value, we can do it using the following statement:

$person = Person::withName('Example');
Blog Logo

Alfonso Jiménez

Software Engineer at Jobandtalent


Published

Image
Back to Overview