Oct
16
2008

OOP: Inheritance and Modifiers

Simply class’s can be parents, and have children we have gone trough this before. This means that if a method used in Class A is needed in Class B we can tell class b to extend from class a. This will give us all the data and methods from both classes that we want.

Create an Array Inheritance

Its easy, after you create the class, you use text ‘extends’ then the class name of the parent. Here we can show an example:

//We first create a New Class, with two Methods
class a{
function test(){
echo 'Class A, Method test';
}
function notest(){
echo 'Class A, Method notest';
}
} 
 
//We can then create anouther Class, to be the chicled of class a.
class x extends a{
function test(){
echo 'Class X, Method test';
}
} 
 
//Now the output from each class
$classa = new a();
$classx = new x();
 
$classa->test();    // Outputs 'Class A, Method Test'
$classa->notest();    // Outputs 'Class A, Method notest'
$classx->test();    // Outputs ' Class X, Method test'
$classx->notest();    //Outputs 'Class A, Method notest'

As you can see in the first two output examples, if a class has a child it still acts normaly. The 3rd example shows us that if a method name is used twice the child takes prominance, the last example shows us why its used. So you can get data from Class A by asking for it in Class X.

Calling a Method from Child

In the examples we seen above, the child class did not request any data from the parent within its code. We asked for the output outside of the class. If you wish to receave data or a method from a parent you have two choices. The first is to call the class and method directly the other is the same exept asking for parent

class classa {
function methoda {
echo 'You got me';
}
class b extends classa {
function test1(){
classa::methoda;
}
function test1(){
parent::methoda;
} 
 
}

As you can see the class has a parent called classa. In the first test you can see we use the parents class direcly with two semi colons and the method we want to use. The other test example does not use the parents name, instead it says parent:: and the method we wish to use.
Both Work.

Modifiers

I have little understanding, Im checking what ppl at gr8 forum SitePoint know about modifiers. Back in 20mins.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 04. Object Oriented Programming |

3 Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS