Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do multiple constructors in PHP

You can't put two __construct functions with unique argument signatures in a PHP class. I'd like to do this:

class Student  {    protected $id;    protected $name;    // etc.     public function __construct($id){        $this->id = $id;       // other members are still uninitialized    }     public function __construct($row_from_database){        $this->id = $row_from_database->id;        $this->name = $row_from_database->name;        // etc.    } } 

What is the best way to do this in PHP?

like image 997
Jannie Theunissen Avatar asked Nov 09 '09 08:11

Jannie Theunissen


People also ask

How can we have multiple constructors in PHP?

Well, the simple answer is, You can't. At least natively. PHP lacks support for declaring multiple constructors of different numbers of parameters for a class unlike languages such as Java. So, if we declare an another constructor in the above example like so.

Can I have 2 constructor?

There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.

What are the __ construct () and __ destruct () methods in a PHP class?

Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.

What is __ construct in PHP?

PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!


1 Answers

I'd probably do something like this:

<?php  class Student {     public function __construct() {         // allocate your stuff     }      public static function withID( $id ) {         $instance = new self();         $instance->loadByID( $id );         return $instance;     }      public static function withRow( array $row ) {         $instance = new self();         $instance->fill( $row );         return $instance;     }      protected function loadByID( $id ) {         // do query         $row = my_awesome_db_access_stuff( $id );         $this->fill( $row );     }      protected function fill( array $row ) {         // fill all properties from array     } }  ?> 

Then if i want a Student where i know the ID:

$student = Student::withID( $id ); 

Or if i have an array of the db row:

$student = Student::withRow( $row ); 

Technically you're not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way.

like image 140
Kris Avatar answered Oct 05 '22 02:10

Kris