hi everyone,
can any body help me knowing that how can i initialize the constructor of the base class if an object of the derived class is created.
eg.
class base
{
var x;
var y;
function base()
{
$this->x = 100;
$this->y = 200;
}
}
class derived extends base
{
var p;
var q;
function derived()
{
$this->p = 20;
$this->q = 40;
}
}
Now if i declare an object of the class derived like this:
$obj = new derived();
The above statement initilizes the constructor of the child class which sets the values of p and q to 20 and 40 respectively,
now i am not able to figure out that how can i initialize and access the variables of the base (parent) class by creating an object of the derived class, so that i am also able to access the variables of the parent class with the same object (i.e. object of the child class)
kindly help,
Thanks
Gaurav
initialzing base class constructor
Moderator: General Moderators
-
gaurav_sting
- Forum Newbie
- Posts: 19
- Joined: Sat Mar 27, 2004 3:45 am
- Location: Delhi
There are a couple of approaches....
Or....
Code: Select all
class base
{
var x;
var y;
function base()
{
$this->x = 100;
$this->y = 200;
}
function _init_base()
{
$this->x = 100;
$this->y = 200;
}
}
class derived extends base
{
var p;
var q;
function derived()
{
$this->p = 20;
$this->q = 40;
$this->_init_base();
}
}Code: Select all
class base
{
var x;
var y;
function base()
{
$this->x = 100;
$this->y = 200;
}
}
class derived extends base
{
var p;
var q;
function derived()
{
$this->p = 20;
$this->q = 40;
$this->x = 100;
$this->y = 200;
}
}- scorphus
- Forum Regular
- Posts: 589
- Joined: Fri May 09, 2003 11:53 pm
- Location: Belo Horizonte, Brazil
- Contact:
Or yet:
which outputs:
-- Scorphus
Code: Select all
<?php
class base {
var $x;
var $y;
function base () {
echo "I'm base()\n";
$this->x = 100;
$this->y = 200;
}
}
class derived extends base {
var $p;
var $q;
function derived () {
$this->base();
echo "I'm derived()\n";
$this->p = 20;
$this->q = 40;
}
}
$obj = new derived;
echo $obj->x ;
?>Code: Select all
I'm base()
I'm derived()
100Yes, that would work. I tend to keep class constructors just as that as there are many times when you don't want the base class initiated on it's own..
Code: Select all
class base
{
var x;
var y;
function base()
{
trigger_error('Failed to initiate base class, unable to find derived', E_USER_ERROR);
}
function _init_base()
{
$this->x = 100;
$this->y = 200;
}
}
class derived extends base
{
var p;
var q;
function derived()
{
$this->p = 20;
$this->q = 40;
$this->_init_base();
}
}