2010-01-27 69 views
2

如何在PHP中模仿C++模板类?如何在php中模仿模板类

EDITED1

例如如何将这个在PHP?

template <typename T> 
class MyQueue 
{ 
     std::vector<T> data; 
     public: 
     void Add(T const &d); 
     void Remove(); 
     void Print(); 
}; 
+1

到底为什么你需要吗?也许PHP有不同的工具可以更好地适应你的目的。 – Sejanus 2010-01-27 15:57:44

回答

1

转换你的C++代码PHP:

class MyQueue{ 
    private $data; 
    public function Add($d); 
    public function Remove(); 
    public function Print(); 
}; 

由于Thirler解释说,PHP是动态的,所以你可以把你想要添加函数的任何信息,并按住要在$数据的任何值。如果你真的想添加一些类型安全,你必须将你想要允许的类型传递给构造函数。

public function __construct($t){ 
    $this->type = $t; 
} 

然后,您可以使用instanceof运算符在其他函数中添加一些检查。

public function Add($d){ 
    if (!($d instanceof $this->type){ 
     throw new TypeException("The value passed to the function was not a {$this->type}"); 
    } 
    //rest of the code here 
} 

但是,它不会来接近设计在编译时捕捉类型错误是静态类型languge的功能。

4

PHP是动态类型。我认为在这种情况下使用模板是不可能的/有用的/有意义的,因为它们只是附加的类型信息。

编辑: 作为对您的示例的回复,在php中,您将负责了解列表中的类型。一切都被列表所接受。

0

PHP具有令人难以置信的有用数组,它接受任何类型作为值,以及任何标量作为键。

你的榜样的最好的翻译是

class MyQueue { 
    private $data = array(); 

    public function Add($item) { 
    $this->data[] = $item; //adds item to end of array 
    } 

    public function Remove() { 
    //removes first item in array and returns it, or null if array is empty 
    return array_shift($this->data); 
    } 

    public function Print() { 
    foreach($this->data as $item) { 
     echo "Item: ".$item."<br/>\n"; 
    } 
    } 

}