Page 1 of 1

initialzing base class constructor

Posted: Tue Jun 29, 2004 9:05 am
by gaurav_sting
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

Posted: Tue Jun 29, 2004 9:12 am
by redmonkey
There are a couple of approaches....

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();
  }
}
Or....

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;
  }
}

Posted: Tue Jun 29, 2004 9:29 am
by scorphus
Or yet:

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 ;
?>
which outputs:

Code: Select all

I'm base()
I'm derived()
100
-- Scorphus

Posted: Tue Jun 29, 2004 9:51 am
by redmonkey
Yes, 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();
  }
}

Posted: Tue Jun 29, 2004 9:58 am
by scorphus
humm... a pseudo-abstract class, isn't it? ;) cool...