PHP OOPs : Class and Object with examples

easy solution web : OOPS in PHP

How can we describe “Class and Object”

According to Wikipedia

“In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).”

So class basically defined the properties and behavior of an object which can be termed as a “template for object”.

According to the defined class, our instantiated object will behave.

For example:-

Let’s we need to create an object for the Pen. For creating an Object of Pen first we need to define it’s property and behavior first. Then and only this pen will come into existence in first place.

So for creating a pen first, we need to define it as a class which consists, what kind of properties and behavior it will have(i.e. its BLUEPRINT).

So let’s define a class for pen first :

If we define a pen class lets define its basic properties which are needed for our pen object

Color(Black,Blue,Red)

Type(Ball, Ink, Gel)

Brand(Reynolds,Jitter,anything)

Now let’s define some behaviors for the pen now, it means pen’s functionality, what will this pen do.

write()
changeColor()

 

 

color, type and brand is known as member variables and write and changeColor is also known as member functions in Class

So how can we implement the concept of class and object in PHP

<?php
class Pen
{
// property declaration
public color = '';
public type = '';
public brand = '';
// method declaration
public function write() {
echo “Write Something!!”;
}
public function changeColor($color){
$this->color = $color;
}
}
?>

This is how we will be able to define a class in PHP. Sometimes it is also called as a concrete class.

Now how can we intantiate an object of pen

Syntax to create an Object

object_variable = new Class_name();

In our example this statement will become:

$reynolds = new Pen();

How can we access property of an object.

echo $reynolds->color; //will write empty string

$reynolds->color = “RED”;  // will change the property color of pen to “RED”

echo $reynolds->color;  //will write RED

How can we access member function of object

$reynolds->write();  //will print Write Something!!

 

This is how we decide how can we create a class for an Object.