简体   繁体   English

将Java hashmap初始化程序转换为PHP等效项

[英]Converting Java hashmap initializer to PHP equivalent

Just curious which way is correct? 只是好奇哪条路是正确的?

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

should this be interpreted in PHP as 应该在PHP中解释为

Class HashMap {}

/**
 * @return this
 */
public function setRequestHeader($key, $value) {
    if ($this->headers == NULL) {
        $this->headers = new HashMap();
    }
    return $this->headers->$key = $value;
}

....or.... ....要么....

/**
 * @return array
 */
public function setRequestHeader($key, $value) {
    if ($this->headers == NULL) {
        $this->headers = array();
    }
    return $this->headers[$key] = $value;
}

if the associative array is correct like I believe, would there be a need for declaring this variable at the top of the class? 如果关联数组是正确的,就像我认为的那样,是否需要在类的顶部声明这个变量?

// JAVA version
private HashMap<String, String> headers;

Would be akin to 就像是

// PHP version
private $headers = array();

Arrays in PHP have a key-value structure...thus is correct: PHP中的数组具有键值结构......因此是正确的:

$this->headers[$key] = $value;

In fact, the PHP manual says: 事实上,PHP手册说:

An array in PHP is actually an ordered map. PHP中的数组实际上是一个有序映射。

http://php.net/manual/de/language.types.array.php http://php.net/manual/de/language.types.array.php

Although, according to How is the PHP array implemented on the C level? 虽然,根据如何在C级实现PHP数组? , it is actually a HashTable , which means you can rely on the O(1) lookup. ,它实际上是一个HashTable ,这意味着你可以依赖O(1)查找。

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

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