Hi

My understanding of classes and inheritance it that when a class extends another class it is able to access the variables and functions of the parent class.

Whilst this concept is easy for me to grasp I am having difficulty in accessing the variables I declared in my parent class in a child class.

In the example below how would I access the $this->year variable so I can use it in the child (Second) class?

At present this code just prints out the month and not the year.

class First {

var $year;

 function First(){
 $this->year = date('Y');
 }
}

class Second extends First {

 var $month_year;

 function Second(){
 $this->month_year = date('M').$this->year;
 }

}



$ob = new Second;
echo $ob->month_year;

I have read part of the PHP manual on classes and objects but there must be something I am not grasping. :bemused:

    Ok I think I have found my answer.

    Within the second function I need to put the code:

    First::First();

    in order to access the $this-year variable.

    I have tried something similar before but placed the First::First(); outside a class function.

    If anyone has any comments on this they would be useful.

      Your right, in order for the construct of your First class to be called, you need to call it in the construct of your Second. The reason is that a parents class's construct isn't called automatically when you create a child class.

        Write a Reply...