Page 1 of 1

[SOLVED] Calling Class A from Class B

Posted: Sat Nov 29, 2003 11:15 pm
by Gen-ik
Does anyone know if it's possible to call/use one Class from another, but reference it with it's object name?

For example, the following won't work and I'm hoping someone can show me how to achive this.

Code: Select all

<?php

class A
{
     function Test()
     {
          echo "BOB";
     }
}

class B
{
     function printBOB()
     {
          $a->Test();
     }
}

$a = new A();
$b = new B();

// I would like the following to print BOB to the page but
// at the moment it won't for obvious reasons.
// Any help would be great.

$b->printBOB();

?>

Posted: Sat Nov 29, 2003 11:40 pm
by BDKR
One way to do it is to use the $GLOBALS array.

Code: Select all

<?php 

class A 
{ 
     function Test() 
     { 
          echo "BOB"; 
     } 
} 

class B 
{ 
     function printBOB() 
     { 
        $GLOBALS['a']->Test(); 
     } 
} 

$a = new A(); 
$b = new B(); 

// I would like the following to print BOB to the page but 
// at the moment it won't for obvious reasons. 
// Any help would be great. 

$b->printBOB(); 

?>
But that's actually a bad pactice. You should really be doing some message passing. However, for one class to pass a message to another requries that it be aware of the others existence. So, something like...

Code: Select all

<?php 

class A 
{ 
     function Test() 
     { 
          echo "BOB"; 
     } 
} 

class B 
{ 
	var $otherClass;	
	
	 function setOtherClass($laOtra)
	  { $this->otherClass=&$laOtra; }
	
     function printBOB() 
     { 
        $this->otherClass->Test(); 
     } 
} 

$a = new A(); 
$b = new B(); 
$b->setOtherClass($a);

// I would like the following to print BOB to the page but 
// at the moment it won't for obvious reasons. 
// Any help would be great. 

$b->printBOB(); 

?>
So based on your post, the first one is what you wanted, but I really don't suggest this. The second option will require less maintenance over time and actually run faster. Additionally, the use of GLOBALS should be avoided if possible.

Cheers,
BDKR

Posted: Sun Nov 30, 2003 12:12 am
by Gen-ik
Thanks for that. I did find myself wondering down the Global path to get it to work so I guess I was half way there... just need to do a sharp-left now into Message Passing.

Cheers mate. :)

Posted: Sun Nov 30, 2003 9:35 am
by BDKR
Right on!