PHP 8.5.0 Alpha 4 available for testing

Voting

: zero plus three?
(Example: nine)

The Note You're Voting On

wassimamal121 at hotmail dot com
10 years ago
The example given by PHP manual is pretty clever and simple.
The example begins by explaining how things go when two aliases referring to the same objects are changed, just rethink the first part of the example
<?php

class A { public $foo = 1;}
function
go($obj) { $obj->foo = 2;}
function
bo($obj) {$obj=new A;}

function
chan($p){$p=44;}
function
chanref(&$p){$p=44;}

/**************manipulating simple variable******************/
$h=2;$k=$h;$h=4; echo '$k='.$k."<br/>";
//$k refers to a memory cell containing the value 2
//$k is created and referes to another cell in the RAM
//$k=$h implies take the content of the cell to which $h refers
//and put it in the cell to which $k refers to
//$h=4 implies change the content of the cell to which $h refers to
//dosn't imply changing the content of the cell to which $k refers to

$h=2;$k=&$h;$h=4; echo '$k='.$k."<br/>";
//here $k refers to the same memory cell as $h

$v=2;chan($v); echo '$v='.$v."<br/>";
//the value of $v doesn't change because the function takes
// as argument an alias refering to a value 2, in the function we
//change only the value to which this alias refers to

$u=2;chanref($u); echo '$u='.$u."<br/>";
//here the value changes because we pass a adress of the
//memory cell to which $u refers to, the function is manipulating
//the content of this memory cell

/***************manipaliting objects************************/
$a = new A;
//create an object by allocating some cells in memory, $a refers
//to this cells

$b = $a;
//$b refers to the same cells, it's not like simple variables
//which are created then, we copy the content

$b->foo = 2;echo $a->foo."<br/>";
//you can access the same object using both $a or $b

$c = new A;$d = &$c;$d->foo = 2;echo $c->foo."<br/>";
//$d and $c don't just refers to the same memory space,
//but they are the same

$e = new A;
go($e);
//we pass a copy of a pointer
echo $e->foo."<br/>";
bo($e);
echo
$e->foo."<br/>";
//if you think it's 1 sorry I failed to explain
//remember you passed just a pointer, when new is called
//the pointer is discoupled
?>

<< Back to user notes page

To Top