/ Gists / 0. Multiple constructors
On gists

0. Multiple constructors

PHP Patterns

multiple.php Raw #

<?php
class File {
	protected $resource;
	
	protected function __construct() {
		// objekt nepůjde zvenku přímo vytvořit
	}
	
	static function createFromFile($filename, $mode) {
		$return = new self; // vytvoří objekt třídy File
		// od PHP 5.3 lze místo self použít static - vytvoří i potomky
		$return->resource = fOpen($filename, $mode);
		return $return;
	}
	
	static function createFromSocket($hostname, $port = -1) {
		$return = new self;
		$return->resource = fSockOpen($hostname, $port);
		return $return;
	}
}

$file = File::createFromFile(__FILE__, "r");

multiple-constructors.php Raw #

<?php

trait constructable
{
    public function __construct() 
    { 
        $a = func_get_args(); 
        $i = func_num_args(); 
        if (method_exists($this,$f='__construct'.$i)) { 
            call_user_func_array([$this,$f],$a); 
        } 
    } 
}

class a {
    use constructable;

    public $result;

    public function __construct1($a){
        $this->result = $a;
    }

    public function __construct2($a, $b){
        $this->result =  $a + $b;
    }
}

echo (new a(1))->result;    // 1
echo (new a(1,2))->result;  // 3

student-example.php Raw #

<?php

// https://stackoverflow.com/questions/1699796/best-way-to-do-multiple-constructors-in-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
    }
}

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