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();
2
  • 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. Commented Mar 18, 2013 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 Commented Mar 18, 2013 at 22:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+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 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 :)
Yeah I thought that this particular scenario interesting enough to be worth asking about?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.