Thursday, March 22, 2007

php4 reference example


<php
class A {
function A($i) {
$this->value = $i;
// try to figure out why we do not need a reference here
$this->b = new B($this);
}

function createRef() {
$this->c = new B($this);
}

function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->value;
}

function thisAfunc(){
echo "<br>this is class A's function. ";
}
}


class B {
function B(&$a) {
$this->a = &$a;
}

function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->a->value;
}

function getAfunc(){
$this->a->thisAfunc();
}

function thisBfunc(){
echo "<br>this is class B's function. ";
}
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
//$a->b->thisAfunc();
//Fatal error: Call to undefined method B::thisAfunc() in /Users/yu/Sites/CakePHP/views/php/reference.thtml on line 43
$a->b->thisBfunc();
$a->c->echoValue();
//$a->c->thisAfunc();
//Fatal error: Call to undefined method B::thisAfunc() in /Users/yu/Sites/CakePHP/views/php/reference.thtml on line 47
$a->c->thisBfunc();
$a->c->getAfunc();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

?>

No comments :