只是好奇哪種方式是正確的?將Java HashMap初始化器轉換爲PHP等效
// the origional JAVA method
public void setRequestHeader(String key, String value) {
if (this.headers == null) {
this.headers = new HashMap<String, String>();
}
this.headers.put(key, value);
}
這應該在PHP中被解釋爲
Class HashMap {}
/**
* @return this
*/
public function setRequestHeader($key, $value) {
if ($this->headers == NULL) {
$this->headers = new HashMap();
}
return $this->headers->$key = $value;
}
.... ....或
/**
* @return array
*/
public function setRequestHeader($key, $value) {
if ($this->headers == NULL) {
$this->headers = array();
}
return $this->headers[$key] = $value;
}
如果關聯數組是正確的喜歡,我相信,會有是否需要在類的頂部聲明這個變量?
// JAVA version
private HashMap<String, String> headers;
將類似於在PHP
// PHP version
private $headers = array();
對於第二個問題,在PHP中使用它之前,你不需要聲明一個'array',所以不需要,它不需要它。這可能是更好的做法。 – Tushar 2013-03-18 22:19:41
是的,它會改變第二種方法(關聯的)來詢問if(empty($ this-> headers))// do stuff'而不是if == == NULL' – ehime 2013-03-18 22:22:23