how to mimic template classes in php
How to mimic C++ template classes in PHP?
EDITED1
For example how would this be in PHP?
template 开发者_高级运维 <typename T>
class MyQueue
{
std::vector<T> data;
public:
void Add(T const &d);
void Remove();
void Print();
};
PHP is dynamicly typed. I don't think it is possible/useful/makes sense to have templates in that case as they are only additional type information.
Edit: As a reply to your example, in php you'd be responsible of knowing the type that is in the list. Everything is accepted by the list.
Converting your C++ code to PHP:
class MyQueue{
private $data;
public function Add($d);
public function Remove();
public function Print();
};
As Thirler explained, PHP is dynamic, so you can pass anything you want to the Add function, and hold whatever values you want in $data. If you really wanted to add some type safety, you would have to pass the type you want to allow to the constructor.
public function __construct($t){
$this->type = $t;
}
Then you can add some checks in other functions using the instanceof operator.
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
}
However, it will not come close to the functionality of a statically typed languge that is designed to catch the type errors at compile time.
PHP has incredibly useful arrays that accept any type as a value, and any scalar as a key.
The best translation of your example is
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";
}
}
}
精彩评论