如何在php中模拟模板类 如何在PHP中模拟C++模板类?< /P>
编辑1 例如,这在PHP中是如何实现的如何在php中模拟模板类 如何在PHP中模拟C++模板类?< /P>,php,class,templates,Php,Class,Templates,编辑1 例如,这在PHP中是如何实现的 template <typename T> class MyQueue { std::vector<T> data; public: void Add(T const &d); void Remove(); void Print(); }; PHP是动态类型的。我认为在这种情况下使用模板是不可能/有用/没有意义的,因为它们只是额外的类型信
template <typename T>
class MyQueue
{
std::vector<T> data;
public:
void Add(T const &d);
void Remove();
void Print();
};
PHP是动态类型的。我认为在这种情况下使用模板是不可能/有用/没有意义的,因为它们只是额外的类型信息 编辑:
作为对示例的回复,在php中,您需要知道列表中的类型。所有的东西都被列表所接受。< /P> < p>将C++代码转换为PHP:< /P>
class MyQueue{
private $data;
public function Add($d);
public function Remove();
public function Print();
};
正如Thirler所解释的,PHP是动态的,因此您可以将任何想要的内容传递给Add函数,并在$data中保存任何想要的值。如果您真的想添加一些类型安全性,那么必须将要允许的类型传递给构造函数
public function __construct($t){
$this->type = $t;
}
然后可以使用运算符在其他函数中添加一些检查
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
}
但是,它不会接近静态类型语言的功能,静态类型语言旨在在编译时捕获类型错误。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";
}
}
}
你到底为什么需要这个?也许PHP有不同的工具更适合您的目的。