New way to learn PHP

PHP 5 Objects

PHP Objects

An object is a specific instance of a class. An object is created by using the new keyword. For example, if you create a Laptop class, you might then go on to create an object called myobject that belongs to the Laptop class. You could then create a second object, yourobj also based on the Car class.


Syntax of PHP 5 Object

$object_name = new Class name;

In the above syntax $object_name is an object variable and new keyword is used for creating an object.

An object based on the class Student can be instantiated as follows: (Student class is shown below.)

Example of object

$Student_detail = new Student();

PHP 5 class and object example


class Student 
public $name;
public $branch;
$a1 = new Student();
$a1-> first_name = "John";
$a1-> branch = "Cse";
echo "Student first_name is " . $a1-> first_name ."
"; echo "Student branch is " . $a1-> branch ."
"; echo " The Object:
"; print_r( $a1 ); ?>


Student first_name is John
Student branch is Cse
The Object:
Student Object ( [name] => [branch] => Cse [first_name] => John )

In this example, we are creating a Student class. Initializing the value of these properties from outside the class with the help of object $a1. And after that displaying the by using object $a1.

Download Source script

Example of class and object that maintain the Student record


class Student 
public $first_name;
public $branch;
public function get($first_name1,$branch1)
$this-> first_name = $first_name1;
$this-> branch =$branch1;
public function display()
echo " The first name of the Student: " . $this-> first_name."
" ; echo " The branch of the student: " . $this-> branch ."
"; } } $a1 = new Student(); $a1->get("John","Cse"); $a1->display(); $a1->get("Umar","Cse"); $a1->display(); ?>


The first name of the Student: John
The branch of the student: Cse
The first name of the Student: Umar
The branch of the student: Cse

In this example, a1 and a2 are the two objects of computer class. Initializing the value of object by using the get function and displaying the data with the help of display function.

Download Source Script


Note: you can create any numbers of object belongs to the same class, they all objects are based on the same class but all are independent.


A single death is tragedy, a million death is a static.