note 20237 deleted from language.references by sniper

From: Date: Tue, 30 Sep 2003 01:17:59 +0000
Subject: note 20237 deleted from language.references by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57307@lists.php.net to get a copy of this message
Note Submitter: vincent@sunlight.tmfweb.NO_SPAM.nl ---- 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).

« previous php.notes (#57307) next »