note 31555 added to language.oop.newref
| From: | jjh at gmx dot at | Date: | Fri, 25 Apr 2003 18:52:33 +0000 |
| Subject: | note 31555 added to language.oop.newref | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-47097@lists.php.net to get a copy of this message | ||
This is another sample script to demonstrate the use of references on objects.
To test the script first replace all <b r> (note the space!) tags by normal
HTML-linke-brakes! Normal line brakes (what a shame!) cannot be shown inside a
php.net-note!!!
<?
// Class C contains instances of class A and class B.
//
// A should "know" B and B should "know" A.
// In other words: Object A should have a Reference on
// object B and vice versa.
class A {
var $a;
var $a_b; // this links to object B
function A() {
$this->a="set by constructor of A";
}
function getToKnowB(&$b) {
$this->a_b =& $b;
}
}
class B {
var $b;
var $b_a; // this links to object A
function B() {
$this->b="set by constructor of B";
}
function getToKnowA(&$a) {
$this->b_a =& $a;
}
}
class C {
var $myA;
var $myB;
function C() {
// Create Objects A and B
$this->myA = new A;
$this->myB = new B();
// "Introduce" A and B to each other
$this->myA->getToKnowB($this->myB);
$this->myB->getToKnowA($this->myA);
// Prove that A and B are using References (not copies!)
echo "Prove that myA->a equals myB->b_a->a<br>";
$this->myA->a = "one";
echo "this->myA->a is set to ".$this->myA->a."<br>";
$this->myB->b_a->a = "two";
echo "this->myB->b_a->a is set to
".$this->myB->b_a->a."<br>";
echo "this->myA->a: ".$this->myA->a."<br>";
echo "this->myB->b_a->a: ".$this->myB->b_a->a."<br>";
echo "<br>";
echo "Prove that myB->b equals myA->a_b->b<br>";
$this->myB->b = "one";
echo "this->myB->b is set to ".$this->myB->b."<br>";
$this->myA->a_b->b = "two";
echo "this->myA->a_b->b is set to
".$this->myA->a_b->b."<br>";
echo "this->myB->b: ".$this->myB->b."<br>";
echo "this->myA->a_b->b: ".$this->myA->a_b->b."<br>";
}
}
$myC = new C;
/*
evaluates to:
Prove that myA->a equals myB->b_a->a
this->myA->a is set to one
this->myB->b_a->a is set to two
this->myA->a: two
this->myB->b_a->a: two
Prove that myB->b equals myA->a_b->b
this->myB->b is set to one
this->myA->a_b->b is set to two
this->myB->b: two
this->myA->a_b->b: two
*/
?>
--
http://www.php.net/manual/en/language.oop.newref.php
http://master.php.net/manage/user-notes.php?action=edit+31555
http://master.php.net/manage/user-notes.php?action=delete+31555
http://master.php.net/manage/user-notes.php?action=reject+31555