0

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

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();
ehime
  • 8,025
  • 14
  • 51
  • 110
  • For your second question, you don't need to declare something as an `array` before using it in PHP, so no, there isn't a "need" for it. It's probably better practice though. – Tushar Mar 18 '13 at 22:19
  • Yeah it would change the second method (the associative one) to ask `if(empty($this->headers)) // do stuff` instead of `if ... == NULL` – ehime Mar 18 '13 at 22:22

1 Answers1

2

Arrays in PHP have a key-value structure...thus is correct:

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

In fact, the PHP manual says:

An array in PHP is actually an ordered map.

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

Although, according to How is the PHP array implemented on the C level? , it is actually a HashTable, which means you can rely on the O(1) lookup.

Community
  • 1
  • 1
Tushar
  • 8,019
  • 31
  • 38
  • 1
    +1. I also believe this is correct, but wanted to see if anyone doesn't believe that associative arrays are PHP's equivalent of hashmaps and why. The only reason I ask is that this is in a Class related OOP scenario. – ehime Mar 18 '13 at 22:14
  • 1
    @ehime Fair enough. I figured you knew the ordered map bit, but I was surprised as well to read that they were implemented as a HashTable. Maybe this will be interesting to others as well :) – Tushar Mar 18 '13 at 22:17
  • Yeah I thought that this particular scenario interesting enough to be worth asking about? – ehime Mar 18 '13 at 22:19