Page 1 of 1

calling a constructor of an extended class

Posted: Sat Oct 18, 2003 9:37 am
by cybaf
Maybe i'm just going at this problem in the wrong way (or thinking too much java) but how would I proceed with the following?

Code: Select all

<?php
class Foo extends Bar {
    function Foo($args='some argument') {
        // do something
    }

    //some other functions
}

class Bar {
    function Bar($arg1=null,$arg2=null) {
        //do some vital stuff
    }
}
?>
How is the Bar constructor called? or do I just to Bar::Bar("arg1","arg2); ??

Posted: Sat Oct 18, 2003 9:49 am
by markl999
If class Foo has no constructor then class Bar's constructor would be called automatically.
To call class Bar's constructor from within class Foo's constructor do
parent::Bar();

See http://php.net/manual/en/keyword.parent.php for more info ;)

Posted: Sat Oct 18, 2003 9:55 am
by cybaf
ahh sweet...:)

tried searching php.net for parent before posting, but it didn't lead me there... well well thanks!

Posted: Sat Oct 18, 2003 10:10 am
by Jay
or even simply: $this->Bar();

Posted: Sat Oct 18, 2003 6:21 pm
by McGruff
Jay wrote:or even simply: $this->Bar();
A small point: this will fall down if you have a method Bar() in Foo().

Cybaf: Bar::Bar() works OK but, as mentioned above, parent::Bar() is better in case you later change the name of the Bar class.

This is probably the link you were looking for:

http://uk.php.net/oop

Posted: Sat Oct 18, 2003 6:50 pm
by Jay
Here's an even smaller point: If you change the name of the Bar class, how does parent::Bar() still work?

Posted: Sat Oct 18, 2003 7:04 pm
by McGruff
Jay wrote:Here's an even smaller point: If you change the name of the Bar class, how does parent::Bar() still work?
:oops: I should think before I post.

If parent::method() was aimed at a method and not the constructor it would survive a name change. If pointed at the constructor, and you changed the name of the class (but not the constructor) it would still work - but of course the constructor name is likely to be changed also as you rightly point out.

Posted: Sun Oct 19, 2003 5:24 am
by cybaf
hehe good points... and some less thought through...:) McGruff: I found that link you gave me before I posted, but I guess I skimmed through it a bit too fast.

A big problem when searching for solutions is that no matter how much I look, I will allways get a better solution here at this awesome forum! :)

the above point about calling parent::method() when method() is the constructor will all be solved with php5... with the nice __construct() default method... then we can change the names as much as we want.