2

The output of this is "24", when I'd expect "44".

class some_class {
    public $array = array();

    public function construct() {
        $this->array[5] = 4;
    }

    public function something() {
        // $this->array at this point is empty, why?
        echo (isset($this->array[5])) ? $this->array[5] : 2;
        $this->array[5] = 4;
        // Here, $this->array holds the value 4 in the key 5 correctly
        echo (isset($this->array[5])) ? $this->array[5] : 2;
    }
}

$some_object = new some_class();
$some_object->something();

Any ideas why my expectations are being shattered?

1
  • 4
    public function construct() should be public function __construct(). Commented Dec 6, 2011 at 23:22

3 Answers 3

9

Your constructor isn't firing it needs to be called:

public function __construct(){
 // constructor
}

otherwise the array fails to initialize.

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

Comments

4

Your question basically boils down to your line at the beginning of something(), asking:

$this->array at this point is empty, why?

This is the case because PHP constructors need to be named __construct, whereas yours is simply named construct.

Comments

2

Your function construct() is never called. You should name it __construct().

Comments

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.