Page 1 of 1

oop question

Posted: Sun Apr 03, 2005 10:05 pm
by neophyte
Okay I've got two classes. Class1 instantiates class2 and calls class2 methods. Is there a way for class2 to call class 1 methods with out instantiating class 1 again?

Posted: Sun Apr 03, 2005 10:13 pm
by feyd
if class1 is static, you can just call class1::method(), otherwise you can pass a reference to the class1 object to class2. However, be VERY careful about circular method calls.

Posted: Sun Apr 03, 2005 10:30 pm
by neophyte
feyd wrote: However, be VERY careful about circular method calls.
What is the danger? What can happen? Bad design?

I've got three classes. The two classes are called and instantiated by the third calling/instantiating class. It works great except in one case one of the other classes has to call a method of the calling/instantiating class. Should I be thinking of someother design for this?

Thanks

Posted: Sun Apr 03, 2005 10:47 pm
by feyd

Code: Select all

<?php

class foo
{
	function foo( $i )
	{
		echo 'foo::foo(): ' . $i . &quote;\n&quote;;
		$this->bar =& new bar( $i + 1, $this );
		$this->foo2( $i );
	}

	function foo2( $i )
	{
		echo 'foo::foo2(): ' . $i . &quote;\n&quote;;
		$this->bar->bar2( $i + 1 );
	}
}

class bar
{
	function bar( $i, &$foo )
	{
		echo 'bar::bar(): ' . $i . &quote;\n&quote;;
		if( $foo !== null )
			$this->foo =& $foo;
	}
	
	function bar2( $i )
	{
		echo 'bar::bar2(): ' . $i . &quote;\n&quote;;
		$this->foo->foo2( $i + 1 );
	}
}

$foo =& new foo(0)

?>

Code: Select all

foo::foo(): 0
bar::bar(): 1
foo::foo2(): 0
bar::bar2(): 1
foo::foo2(): 2
bar::bar2(): 3
foo::foo2(): 4
bar::bar2(): 5
foo::foo2(): 6
bar::bar2(): 7
foo::foo2(): 8
bar::bar2(): 9
foo::foo2(): 10
bar::bar2(): 11
foo::foo2(): 12
bar::bar2(): 13
foo::foo2(): 14
bar::bar2(): 15
foo::foo2(): 16
bar::bar2(): 17
foo::foo2(): 18
bar::bar2(): 19
foo::foo2(): 20
bar::bar2(): 21
foo::foo2(): 22
bar::bar2(): 23
foo::foo2(): 24
bar::bar2(): 25
foo::foo2(): 26
bar::bar2(): 27
foo::foo2(): 28
bar::bar2(): 29
foo::foo2(): 30
bar::bar2(): 31
foo::foo2(): 32
bar::bar2(): 33
foo::foo2(): 34
bar::bar2(): 35
foo::foo2(): 36
bar::bar2(): 37
foo::foo2(): 38
bar::bar2(): 39
foo::foo2(): 40
basically it's an infinite call loop..

Posted: Sun Apr 03, 2005 10:51 pm
by neophyte
Okay I'll watchout for that. Thanks for the tip feyd.