admin Site Admin
Joined: 28 Feb 2006 Posts: 24
|
Posted: Wed Mar 01, 2006 6:47 pm Post subject: PHP4 References (yuk) |
|
|
If you're still using PHP version 4, you should know about PHP Variable References (as I like to call them). In PHP4, you cannot store a reference to an object, but you can store a reference to another variable. You can also think variable references as aliases to other variables. The following example illustrates the behavior of variable references:
| Code: |
<?php
// Store AClass object in $x
$x = new AClass();
// $r will reference the variable $x
$r =& $x;
// These evaluate the same
$x->aMethod();
$r->aMethod();
// Change $x to contain a string instead.
$x = "goodness";
// This would work with object references, but since
// $r is an alias for $x, this won't work.
$r->aMethod();
?>
|
This should illustrate the (gross) use of the & operator in PHP 4. I'm glad to say that PHP 5 has adopted Java-style object references, along with assign/pass by reference by default. From the PHP 5 manual (http://www.php.net/manual/en/migration5.oop.php):
| Quote: |
In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or pass as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).
|
This example illustrates the new and old semantics:
| Code: |
<?php
class MyClass {
var $x;
function MyClass() {
$this->x = "my class";
}
}
$obj = new MyClass;
// This outputs "my class"
echo $obj->x;
$blah = $obj;
$blah->x = "blah!";
// In PHP4, this outputs "my class"
// In PHP5, this outputs "blah!"
echo $obj->x;
?>
|
|
|