Hi to all,
I was wondering if someone out there has had the same
problem as I have; fetching from an object a private array variable
through a get method. And instead of getting a copy of
the array, you get access to the original array, being able to access
the object's internal data!
I have tried my test script on a Linux 2.6.5 running PHP 5.0.4 and
on a FreeBSD 5.4 running PHP 5.0.5 obtaining the same results
on both systems. Bellow is the test script:
==
#!/usr/local/bin/php
?php
class Atom {
private $x=0;
public function __construct($x) {
$this-x = $x;
}
public function setX($x) {
$this-x = $x;
}
public function getX() {
return $this-x;
}
}
class Element {
private $atoms = array();
public function __construct($NMAX) {
for ($i = 0; $i $NMAX; ++$i)
$this-atoms[] = new Atom($i);
}
public function setAtoms($atoms) {
$this-atoms = $atoms;
}
public function getAtoms() {
return $this-atoms;
}
}
echo Starting testing on returning private member array variables\n;
echo System details: PHP .PHP_VERSION. on .PHP_OS.\n;
$element = new Element(3);
$v = $element-getAtoms();
print_r($v);
$v[0]-setX(79);
print_r($v);
$w = $element-getAtoms();
print_r($w);
echo Testing finished\n;
?
==
The results are :
==
Starting testing on returning private member array variables
System details: PHP 5.0.4 on Linux
Array
(
[0] = Atom Object
(
[x:private] = 0
)
[1] = Atom Object
(
[x:private] = 1
)
[2] = Atom Object
(
[x:private] = 2
)
)
Array
(
[0] = Atom Object
(
[x:private] = 79
)
[1] = Atom Object
(
[x:private] = 1
)
[2] = Atom Object
(
[x:private] = 2
)
)
Array
(
[0] = Atom Object
(
[x:private] = 79
)
[1] = Atom Object
(
[x:private] = 1
)
[2] = Atom Object
(
[x:private] = 2
)
)
Testing finished
==
Is this expected behavior, or shouldn't the third Array print-out
have also a zero in its first objects's x variable? Thanks to everyone for
their time.
--Best regards
FNanDO