inheritance question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Guy
Forum Commoner
Posts: 53
Joined: Sun Jan 12, 2003 3:34 am

inheritance question

Post by Guy »

I have classes inheritance something like this small example

Code: Select all

<?PHP
class A
&#123;
	function A()
	&#123;
		$this->dosomething();
	&#125;
	
	function dosomething()
	&#123;
		echo "in A<br>";
	&#125;
&#125;

class B extends A
&#123;
	function B()
	&#123;
		$this->A();      //will print 'in B'
		$this->dosomething();   //will print 'in B'
		A::A();    //will print 'in B'
		A::dosomething(); //will print 'in A'
		
	&#125;
	
	function dosomething()
	&#123;
		echo "in B<br>";
	&#125;
&#125;

$b = new B;

?>
look at the comment in the constructor of B, i want (if there is a away )
to call the constructor of A from B and still call dosomthing function of A and not B.
can it be done?
Thanks
Guy
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

Since the constructor in A simply calls the function dosomething() from A, then you can just call this function from B:

A::dosomething();

Since you redefine dosomething() in B, the constructor of A::A() will be calling the B::dosomething(). This is just how inheritance works and there's no real way to get around it.
bionicdonkey
Forum Contributor
Posts: 132
Joined: Fri Jan 31, 2003 2:28 am
Location: Sydney, Australia
Contact:

Post by bionicdonkey »

since A is the parent class of B use would use:

parent::dosomething();
Post Reply