note 24491 added to ref.classobj
| From: | justin at quadmyre dot com | Date: | Mon, 19 Aug 2002 13:38:51 +0000 |
| Subject: | note 24491 added to ref.classobj | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-35193@lists.php.net to get a copy of this message | ||
If you want to be able to call an instance of a class from within another class, all you need to do
is store a reference to the external class as a property of the local class (can use the constructor
to pass this to the class), then call the external method like this:
$this->classref->memberfunction($vars);
or if the double '->' is too freaky for you, how about:
$ref=&$this->classref;
$ref->memberfunction($vars);
This is handy if you write something like a general SQL class that you want member functions in
other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.
Justin
Example:
<?php
class class1 {
function test($var) {
$result = $var + 2;
return $result;
}
}
class class2{
var $ref_to_class=''; # to be pointer to other class
function class1(&$ref){ #constructor
$this->ref_to_class=$ref; #save ref to other class as property of this class
}
function test2($var){
$val = $this->ref_to_class->test($var); #call other class using ref
return $val;
}
}
$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2
$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);
?>
--
http://www.php.net/manual/en/ref.classobj.php
http://master.php.net/manage/user-notes.php?action=edit+24491
http://master.php.net/manage/user-notes.php?action=delete+24491
http://master.php.net/manage/user-notes.php?action=reject+24491