Voting

: seven minus one?
(Example: nine)

The Note You're Voting On

justin at quadmyre dot com
22 years ago
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);

?>

<< Back to user notes page

To Top