<?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");
<?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