views:

52

answers:

2

I am new to PHP and programming in general. I have been working on a few things with PHP that have required me to create classes, which has been fine, except that I can't seem to get my class methods to work on arrays that are properties of the class. I must be doing something pretty fundamentally wrong, because it doesn't seem to work regardless of the project.

Here is an example I just wrote up (I thought it would be easier to post a short and simple example rather than the code of my actual project, which is kind of long and involved).

class Test {
    public $testArray;
    public $testInt;

    public function __construct() {
        $this->testArray = array();
        for ($i=1; $i<=20; $i++) {
            $this->testArray[] = array(1, 2);
        }
        $this->testInt = 4;
    }

    public function testf() {
        $this->testInt += 1;
        foreach ($this->testArray as $n) {
            $n[] = 3;
        }
    }
}

If I add some code at the end so that I get a print out of what is happening:

$obj = new Test;

echo 'Before function call:';
echo '<br />testArray:<br />';
foreach ($obj->testArray as $n) {
    print_r($n);
    echo '<br />';
}
echo '<br />testInt: ';
echo $obj->testInt;
echo '<br />';
echo '<br />';
echo '<br />';

$obj->testf();

echo 'After function call:';
echo '<br />testArray:<br />';
foreach ($obj->testArray as $n) {
    print_r($n);
    echo '<br />';
}
echo '<br />testInt: ';
echo $obj->testInt;
echo '<br />';

Then what you end up seeing is that after the function call the testInt variable changes, but the testArray doesn't.

Please let me know if any of this isn't clear enough. This has been driving me crazy for a while. Thank you in advance for taking the time to have a look at my problem.

+3  A: 

When you do this:

    foreach ($this->testArray as $n) {
        $n[] = 3;
    }

You're not modifying testArray's values. You're working on copies of them. Any time you assign a value in PHP to another variable, you're making a copy of the value. (Objects are sort of an exception to this, but that's not relevant here.)

If you want to modify the original, you'll need to refer to it by its own variable name, like this:

    foreach ($this->testArray as $index => $value) {
        $this->testArray[$index][] = 3;
    }
JW
Thanks thats really helpful, really appreciate it.
Noah
+3  A: 

You need to add a little something to the foreach loop:

  foreach ($this->testArray as &$n) {
        $n[] = 3;
    }

That should do it. &$n means reference the array element rather than copy it. You probably also want to change $n[] to just $n if you want to overwrite it.

Ben
Ben, your elegant answer did not go unnoticed by me :D
macek