Re: [php-objects] calling another class method

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Monday, February 24, 2003, at 08:12 PM, Christopher Hendry wrote:

> class B {
>
>     function doSomthing()
>     {
>         if (class_exists('A')) {
>         // here I do something, but I also want to call the increment 
> method
> in class A
>         // how do I get name of the object in order to reference the 
> method?
>         // I can hard code this in:
>         $myA->increment();
>         // but this is no good in the long run
>         } else {
>         // throw error as class A does not exist
>         }
>
>     }
>
> }
>

Try passing in the object by reference--that way you operate on the 
object itself, not a copy.

class B
{
	function doSomething(&$ObjA)
	{
		if (is_object($ObjA))
		{
			$ObjA->increment();
			return true;
		}
		else	
		{
			trigger_error("ObjA, she is no good", E_USER_WARNING);
			return false;
		}
	}
}

$a->setNumber(1);
$a->increment();
echo $a->getNumber(); // echoes 2
$b = new B();
$b->doSomething($a);
echo $a->getNumber(); // echoes 3

Another, possibly more OOP, way, if you don't want to explicitly track 
the name of it, is to implement the Singleton pattern in class A, and 
make it a static method.

class B
{
	function doSomething()
	{
		if (is_class('A'))
		{
			$ObjA =& A::singleton();
			$ObjA->increment();
			return true;
		}
		else	
		{
			trigger_error("Class A, she is no good", E_USER_WARNING);
			return false;
		}
	}
}

See <http://www.phppatterns.com/index.php/article/articleview/6/1/1/> 
for more on how to create a singleton.

--
Sandy Smith, Senior Programmer
Forum One Communications
<ssmith@forumone.com>
http://www.forumone.com/
tel. (703) 548-1855 x28


------------------------ Yahoo! Groups Sponsor ---------------------~-->
Get 128 Bit SSL Encryption!
http://us.click.yahoo.com/FpY02D/vN2EAA/xGHJAA/saFolB/TM
---------------------------------------------------------------------~->

Look here for Free PHP Classes of objects:
http://phpclasses.UpperDesign.com/
To unsubscribe from this group, send an email to:
php-objects-unsubscribe@egroups.com

 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 



[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Soap]     [Kernel Newbies]     [Yosemite]     [Yosemite Campsites]

  Powered by Linux