
25-05-2008, 16:12
|
|
|
|
חבר מתאריך: 27.10.05
הודעות: 1,067
|
|
אין לי מידע מהאתר של PHP אבל הנא מהאתר של ZEND
http://devzone.zend.com/article/171...-PHP-5#Heading3
ציטוט:
קוד PHP:
class Person {
var $name;
function getName() {
return $this->name;
}
function setName($name) {
$this->name = $name;
}
function Person($name) {
$this->setName($name);
}
}
function changeName($person, $name) {
$person->setName($name);
}
$person = new Person("Andi");
changeName($person, "Stig");
print $person->getName();
In PHP 4, this piece of code would print out "Andi". The reason is that we pass the object $person to the changeName() function by-value, and thus, $person is copied and changeName() works on a copy of $person.
This behavior is not very intuitive, as many developers would expect the Java-like behavior. In Java variables actually hold a handle (or pointers) to the object, and therefore, when it is copied only the handle and not the entire object is duplicated.
There were two kinds of users in PHP 4, the ones who were aware of this problem and the ones who weren't. The latter would usually not notice this problem and their code was written in a way where it didn't really matter if the problem existed or not. Surely some of these people had sleepless nights trying to track down weird bugs which they couldn't pinpoint. The former group dealt with this problem by always passing and assigning objects by reference. This would prevent the engine from copying their objects but would be quite a headache as the code included numerous & signs.
The old object model not only led to the above-mentioned problems but also led to fundamental problems that prevented implementing some additional features on top of the existing object model.
In PHP 5, the infrastructure of the object model was rewritten to work with object handles. Unless you explicitly clone an object by using the clone keyword you will never create behind the scene duplicates of your objects. In PHP 5, there is neither a need to pass objects by reference nor assigning them by reference.
Note: Passing by reference and assigning by reference is still supported, in case you want to actually change a variable's content (whether object or other type).
|
ד"א מה שמוזר זה שב PHP5 כבר אין צורך להיתשמש ב var לפני משתנה מחלקה, כמו כן ניתן להישתמש ב __construct() בשביל פונקצית בנאי במקום בשם של המחלקה, מוזר שבדוגמא שלהם הם עדיין משתמשים בסינטקס של PHP4.
נערך לאחרונה ע"י eXtruct בתאריך 25-05-2008 בשעה 16:14.
|