I am learning OOP’s PHP by reading the php offical documents
first:
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
Second:
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
Result:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
This example I dont understand about assgined by reference and value
here .even I see the result output.But I still not get an idea.
My question is why $instance and $reference become null?
PHP references operate in a funny way. I’m going to break out a real-life analogy.
Imagine you have a cup. The cup is full of water.
The cup is a variable. The water is the contents of the variable.
Any references you create point at the cup, not the water.
If you replace the water in the cup with coffee, then all of the references to that cup suddenly contain the same coffee.
And when you empty the cup out, all of the references to the cup are suddenly empty.
Now, objects are quite fun. You see, when you assign them to variables, it actually does so kind of by reference. But objects-by-ref aren’t normal references. From the PHP interactive prompt:
Not what you expected, right? It gets funnier.
That is a bit more expected. But is this?
As you can see, even though we completely emptied out the variable containing the reference to our object, the original object was untouched, even though that object was placed into the copy by reference!
Welcome to PHP, where things like this are normal. I suggest frequent checks of your own sanity.
Edit: Oh, one more thing. If you need to make a real copy of the object, you have to
cloneit:It also works on refs:
Oh, and before someone asks: In some languages, references work at the value level, not the variable level. Perl is a good example here. If you create a reference to a variable, then reassign the original, the reference still contains the original value. I came to PHP through Perl, and this seemingly small difference drove me up the wall.