Page 1 of 1

Class Inheritance issue

Posted: Wed Oct 24, 2007 3:51 pm
by mzfp2
Hi,

I recently decided to upgrade to PHP 5, and wiith all the new ))) features I thought it was time to rewrite some of my existing code. However I've ran into a problem when inherting (exttending) a class from a base class.

I define my base class:

Code: Select all

class TForm 
{
    public $Name;

   function __construct($name)
  {  
       $this->Name = $name;
  }

   function createControls()
  {
        $TextBox1 = "Hello World";
  }
}
I then define my child class:

Code: Select all

class TForm_NewStaff
{
     public  $TextBox1;
}


I have simplified my classes for clarity, the problem I am having is that the child class define additional public variables, such as $TextBox1. The child class also inherits the function createControls(). I require the function createControl() in the base class to have access to $TextBox.. I would therefore try something like this in my code.

Code: Select all

$frm_NewStaff = TForm_NewStaff
      $frm_NewStaff->createControls();
from the code above, I would expect $from_NewStaff->TextBox1 to be set to "Hello World"

But naturally, I cannot get this to happen! Is it possible?

Thanks
Musaffar Patel

Posted: Wed Oct 24, 2007 4:18 pm
by seppo0010
Hi, I think you have an error on you code

Code: Select all

/*
   function createControls()
  {
        $TextBox1 = "Hello World";
  } 
should be
*/
   function createControls()
  {
        $this->TextBox1 = "Hello World";
  }
This way whould work.
However, if the base class uses TextBox1 var, why isn't it declared in it, and it's on the child class? I think it should be on the base class..

Re: Class Inheritance issue

Posted: Wed Oct 24, 2007 4:27 pm
by nathanr
to expand a little:

1: class TForm_NewStaff should extend class TForm
2: $TextBox1 should be declared in class TForm
3: the $this keyword needs to be used
4: functions need to be declared public, protected private
5: constucts are overwritten by child class __constucts

thus re-written:

Code: Select all

class TForm 
{
    public $Name;
    public $TextBox1;

   public function __construct($name)
  {  
       $this->setName($name);
  }

   public function setName($name)
  {  
       $this->Name = $name;
  }
  
   public function createControls()
  {
        $this->TextBox1 = "Hello World";
  }
}
child class:

Code: Select all

class TForm_NewStaff extends TForm
{
   public function __construct($name)
  {  
       $this->setName($name);
  }
}

Code: Select all

$frm_NewStaff = new TForm_NewStaff
      $frm_NewStaff->createControls();

that should do the trick for you. it's worth reading the php 5 manual on objects and constuctors also

regards

nathan