2010-01-27 7 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

답변

1

PHP로 C++ 코드를 변환 : 당신은 당신이 추가 기능으로 원하는 무엇이든을 통과, 당신은 $에게 데이터에서 원하는 값 무엇이든지 수용 할 수 있도록

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

} 
관련 문제