|
-
July 18th, 2009, 02:15 AM
#1
PHP: __construct() question
Hello php gurus
If a class has a method named after the class, is the function constructor?
If I have a base class as
PHP Code:
// Inheritance test
class Animal
{
function __construct($ref)
{
$this->animalName = $ref;
}
function eat()
{
printf("%s is eating<br />", $this->animalName);
}
protected $animalName;
}
and I'd like to call the base's constructor in the derived
PHP Code:
//
class Panda extends Animal
{
function __construct($ref)
{
$this->Animal($ref); //works only if Animal($ref) is defined in the base
}
function eat()
{
printf("Big %s is eating<br />", $this->animalName);
return $this;
}
function yawn()
{
printf("Big %s is yawning<br />", $this->animalName);
}
}
What is the difference between __construct() and the function with the same class name?
Thanks for the help.
Last edited by potatoCode; July 18th, 2009 at 02:19 AM.
Reason: changed to the proper php tag
-
July 18th, 2009, 09:37 AM
#2
Re: PHP: __construct() question
If no constructor method is found, then a function that has the same name as the class itself becomes the constructor.
If the post was helpful...Rate it! Remember to use [code] or [php] tags.
-
July 18th, 2009, 04:24 PM
#3
Re: PHP: __construct() question
Hi PeejAvery
 Originally Posted by PeejAvery
If no constructor method is found, then a function that has the same name as the class itself becomes the constructor.
I see.
Then, how do I initialize base member in the derived class
when the base class only uses __construct?
because $this->__construct($ref); doesn't work.
-
July 19th, 2009, 04:08 PM
#4
Re: PHP: __construct() question
You could just create a new instance of the class and then unset it.
If the post was helpful...Rate it! Remember to use [code] or [php] tags.
-
July 19th, 2009, 07:19 PM
#5
Re: PHP: __construct() question
 Originally Posted by PeejAvery
You could just create a new instance of the class and then unset it.
Hm, does that mean a ctor with the same class name serves as a better base class ctor
than __construct() when the dervied class has the need to intialize its base members?
Is that the only difference between the named ctor and __construct()?
-
August 21st, 2009, 07:40 PM
#6
Re: PHP: __construct() question
The child class (panda) can call the parent's constructor using:
PHP Code:
parent::__construct($ref)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|