2015-05-11 125 views
-1

我想通過一個類作爲參數,但我不知道它是否可能。通過一個類作爲參數

class User { 
    var $name; 
} 

class UserRepository { 
    private $type; 
    public function __construct(Class) { 
    $this->type = Class; 
    } 

    public function getInstance() { 
    return new $this->type; 
    } 
} 

$obj = new UserRepository(User); 

我接受其他方式的建議。

回答

1

我想你只是尋找的字符串:

class User { 
    var $name; 
} 

class UserRepository { 
    private $type; 
    public function __construct($Class) { 
           ^^^^^^ this will be a string 
    $this->type = $Class; 
    } 

    public function getInstance() { 
    return new $this->type; 
    } 
} 

$obj = new UserRepository('User'); 
          ^^^^^^ send a string here 

var_dump($obj->getInstance()); 

輸出:

對象(用戶)#2(1){[ 「名稱」] => NULL}

An example

+0

將與命名空間的工作,它呢? –

+0

@TafarelChicotti它適用於您的示例,您將不得不親自嘗試命名空間。 – jeroen

3

只需實例化類並調用

$user = new User(); 
$obj = new UserRepository($user); 

另一種選擇(因爲User只包含變量)是使變量static和使用

class User { 
    public static $name; 
} 
$obj = new UserRepository(User::$name);