Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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?
by

3 Answers

rahul07
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.
RoliMishra
PHP is a dynamic language, so you can't overload methods. You have to check the types of your argument like this:

class Student 
{
protected $id;
protected $name;
// etc.

public function __construct($idOrRow){
if(is_int($idOrRow))
{
$this->id = $idOrRow;
// other members are still uninitialized
}
else if(is_array($idOrRow))
{
$this->id = $idOrRow->id;
$this->name = $idOrRow->name;
// etc.
}
}
pankajshivnani123
public function __construct() {
$parameters = func_get_args();
...
}

$o = new MyClass('One', 'Two', 3);


Now $paramters will be an array with the values 'One', 'Two', 3.

Edit,

I can add that

func_num_args()

will give you the number of parameters to the function.

Login / Signup to Answer the Question.