note 20237 added to language.references
| From: | vincent at sunlight dot tmfweb dot NO_SPAM dot nl | Date: | Wed, 27 Mar 2002 09:37:41 +0000 |
| Subject: | note 20237 added to language.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-28267@lists.php.net to get a copy of this message | ||
For the Java programmers among you, there's a big difference between Java and PHP. In Java, all
objects are passed by value (as in PHP). However, try this in PHP:
class Object {
var $value;
function Object() {
$this->value = 5;
}
function getValue() {
return $this->value;
}
function setValue($value) {
$this->value = $value;
}
}
function updateObject($object) {
$object->setValue($object->getValue() + 5);
echo ', ', $object->getValue();
}
$object = new Object();
echo $object->getValue();
updateObject($object);
echo ', ', $object->getValue();
It prints: '5, 10, 5'.
If you implement this same code in Java however, it will print '5, 10, 10'!
Explanation: 'passing by value' in Java means that assigning a different value to a
variable inside a function will not change it outside a function. (PHP equivalent: '$object =
new Object'.) But calling methods on the variable (when it's an object) can change the
object (In PHP: '$object->setValue(9)'). With PHP the latter isn't true,
unfortunately.
If you use objects in PHP, you have to use references almost all the time, even if you don't
want to assign a new value to an outside variable, but just want to call methods (that might update
the object).
--
http://www.php.net/manual/en/language.references.php
http://master.php.net/manage/user-notes.php?action=edit+20237
http://master.php.net/manage/user-notes.php?action=delete+20237
http://master.php.net/manage/user-notes.php?action=reject+20237