oop question

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

oop question

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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..
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

Okay I'll watchout for that. Thanks for the tip feyd.
Post Reply