繁体   English   中英

如何模仿php中的模板类

[英]how to mimic template classes in php

如何模仿PHP中的C ++模板类?

EDITED1

例如,在PHP中会如何?

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

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

编辑:作为对您的示例的答复,在php中,您将负责了解列表中的类型。 列表接受所有内容。

将您的C ++代码转换为PHP:

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;
}

然后,您可以使用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
}

但是,它不会接近旨在在编译时捕获类型错误的静态类型的语言的功能。

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";
    }
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM