How To Declare Class And Object In PHP

In this tutorial we will see how to create class and object in php. A class is a blue print of an object and an object is a instance of a class. let's see the example to understand better. 

Defining PHP Class 

A class is defined by using the class keyword. The general form defining a class in PHP .

class Car{
	public $color;
	public $company;
}

 

Here Car is class name $ it's contains several properties such as color,model,engine capacity.those properties access by creating an object. 

 

How to create object of a class

We can create several objects from the same class, with each object having its own set of properties.

Objects of a class is created using the new keyword.

$bmw = new Car()
$marcedes= new Car()

 

We can create as many objects as we would like from the same class and they all will share the class's methods and properties.From the same Car class, we created two individual objects with the name of: $bmw, $marcedes.

How to get an object's properties?

$bmw->color

 

In order to get a property, we write the object name, and then dash greater than (->), and then the property name.

 

How to set the object's properties?

In order to set an object property, we use a similar approach.

For example, in order to set the color to 'black' in the bmw object and 'yellow' in the mercedes object.

$bmw->color = 'Black'
$marcedes->color = 'Yellow'

 

Once we set the value of a property, we can get its value. In order to get the color of the $bmw and $mercedes object, we use the following line of code:

echo $bmw->color

 

Result: Black

Example-1

class Car{ //defining a Car class
	public $color;
	public $company;
}
$bmw      = new Car(); //defining a object
$marcedes = new Car();

$bmw->color = 'Black'; // set properties value 
$marcedes->color = 'Yellow';

$bmw->company = 'BMW';
$marcedes->company = 'Marcedes-Benz';

echo $bmw->company; 
echo $bmw->color;

echo $marcedes->company; 
echo $marcedes->color; 

 

Here $bmw and $marcedes objects were created from the same Car class and thus have the class's methods and properties, they are still different. This is not only, because they have different names, but also because they may have different values assigned to their properties.

 

php
Result : BMW Black
Mercedes-Benz Yellow

 

Hope you will understand. 

 

#php #oop