1

I am new to PHP OOP and I am having problem getting arrays back.

class example
{
    public $array;

    public function __construct()
    {
        $this->array = array();

    }

    public function do_work()
    {
        $this->array[] = 'test';
    }
}
$test = new example();
$test->do_work();
$test->array;

I keep getting a empty array instead of 'test'. What am I doing wrong?

8
  • new example() would create the object with the array and $test->array will technically allow you access the array but if you don't call $test->do_work(); the array will not contain anything. Commented May 11, 2012 at 19:59
  • 1
    Perhaps you meant to invoke do_work() in the constructor? Also, it's never a good idea to use protected keywords for variable names. Commented May 11, 2012 at 20:00
  • @Ansari: I disagree with both of your statements. Please do explain. Commented May 11, 2012 at 20:03
  • Sorry guys, I just added do_work(). Commented May 11, 2012 at 20:04
  • @BlakeJeffery: Your code (as it is, literally copy pasted) works flawlessly. Are you sure that is your entire code? Commented May 11, 2012 at 20:05

2 Answers 2

5

This is because you never actually call the function $test->do_work(); The constructor just creates the empty array, and then you attempt to access the property. It should be empty.

Updates

I see you updated your question. If you simply echo $test->array, it should just print Array. However, when I copy your updated code and perform a var_dump($test->array), this is the output I get:

array(1) { [0]=> string(4) "test" } 

Which I believe is what you are expecting. The code that you have in your question, though, should output nothing. You are doing nothing with $test->array, the variable is being evaluated and then thrown away.

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

2 Comments

Note that in the original answer, OP didn't have $test->do_work() in his code. It's not shown due to the edit grace period.
@Blake no problem, glad we could help.
4

Your last statement, $test->array; doesn't actually do anything. My guess is that you are using something like echo. Your code should output the array if you use for example var_dump, see the example on codepad

Comments

Your Answer

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