QAds
Apple iPod nano 8 GB Yesil
$88.21
Apple iPod nano 8 GB Mavi
$88.21
Apple iPad 64gb Wi-Fi
$648.97
Apple iPod shuffle 1 GB Pembe
$35.00
:: HOME PHP OOP Object Oriented Programming
 
OOP Object Oriented Programming

Nowadays, we can hear mostly about object oriented programming. The main aim of using OO programming is to call states and behaviors from one source. States(Variables)  and behaviors(Functions) forms an object. For example, lets think of a car. It has a model, color, number of doors, weight. These are status. Moreover, starting, moving, changing transmission and stopping are car's behaviors. As you see, you can change car's model, color but you cant change its behaviors. Here, a car is an object and car is a class.

 

Lets see how to define a class and use it.

 

Class car

{

Var $brand;

Var $color;

 

Function car()

{

 

}

 

Function start()

{

Echo 'start';

}

 

Function stop()

{

Echo 'stop';

}

 

Function show()

{

Echo 'Brand: '.$this->brand;

Echo 'Color: '.$this->color;

}

 

}

 

 

We define our class name with class and we start to define variables and create functions we need to use. If we want to reach class variables or function in a function we need to use $this. $this defines current class. 

 

If you use class name as a function, it means when we create an object with our class, initially this function will be activated. We don’t need to use it but if do, it will be activated when we create an object with our class.

 

Then, we can use our class like below :

 

$myCar= new car; we create an object

 

$myCar->brand= 'bmw'; we define our class variable

$myCar->start();

$myCar->stop();

$myCar->show();

 

$myNewCar= new car; we can create as many as we want

$myNewCar->brand= 'mercedes';

$myNewCar->color= 'blue';

$myNewCar->show();

 

At first object, we can see blank color info because we haven't defined any color for this object. To prevent this, we can use default variable values. For that, we need to use our initial function.

 

Function car()

{

$this->brand= 'ferrari';

$this->color= 'blue';

}

 

If we want to improve our class, we don’t need to go to file and modify it. We can create a class from current class.

 

Class featured_car extends car

{

Function change_transmision()

{

Echo 'change transmision';

}

}

 

$myCar= new featured_car;

 

$myCar->start();

$myCar->change_transmission();

$myCar->stop();

 

To be able to reach variables and functions of first class, we have 3 ways. First way is that we can use $this. Other way is we can use parent like parent::FunctionName. Parent means the class which we used to create new class. Instead of parent we can use class name too. ClassName::FunctionName.