...

View Full Version : referencing a class inside another class



johnrau
06-07-2004, 12:02 AM
hi, i've been trying to use the functionality of one class inside another:

should the following code work in theory?



class out {
var $output = "yay";
function put() {
echo $this->output;
}
}

class test {
function testme() {
global $out;
$out->put();
}
}

$out = new out;
$test = new test;

$test->testme();


the above should output yay, right?

thanks
j

MrShed
06-07-2004, 12:57 AM
i dont THINK its right in theory, in fact fairly sure it isnt. But then I don't know how to do it either so i cud b wrong :rolleyes:

firepages
06-07-2004, 03:43 AM
well it works , though in general OO advocates try to avoid globals where possible

2 more commonly use options are ,
1) to pass the object to the constructor (or indeed a class method)


<?
class out {
var $output = "yay";
function put() {
echo $this->output;
}
}

class test {
function test( $obj ){
$this->obj=$obj;
}
function testme() {
$this->obj->put();
}
}

$out = new out;
$test = new test($out);

$test->testme();
?>


or 2) 'aggregate` the class.



<?
class out {
var $output = "ya2y";
function put() {
echo $this->output;
}
}

class test {
function test( ){
$this->out=new out;
}
function testme() {
$this->out->put();
}
}

$test = new test( );
$test->testme();
?>


ehat you use and when you use it will depend on many factors.

johnrau
06-07-2004, 03:50 PM
Thank you sir!
Your code has been much helpful!

Have a good one!

-John



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum