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.