Friday, April 24, 2009

PHP5 Tutorial - Learn to Create a PHP5 Class Object


In the earlier PHP5 OOPS tutorial you learnt how to create a class in PHP5. In this tutorial you will learn how to create an object of a PHP5 class. But before we begin, lets understand what is an object.

Definition of an Object
An object is a living instance of a class. This means that an object is created from the definition of the class and is loaded in memory. A good analogy to understand this is to compare objects with humans - and understand that all of us (you and I) are objects. If God wants to send a human to earth, what is easy for Him to do? Create and define properties and attributes of each human separately or create a one time template and generate objects out if it. Therefore, this onetime template is a Class and you, I & everyone in this world is an object - that is a living instance of class Human.


Creating Objects in PHP5 Class

To create an object of a PHP5 class we use the keyword new. Below is the syntax style of how to create objects in PHP5:

        $obj_name = new ClassName();

In the above syntax style, $obj_name is a variable in PHP. ‘new’ is the keyword which is responsible for creating a new instance of ClassName.

Look at the example below:

class Customer {
private $first_name, $last_name;

public function getData($first_name, $last_name) {
$this->first_name = $first_name;
$this->last_name = $last_name;
}

public function printData() {
echo $this->first_name . " : " . $this->last_name;
}
}

$c1 = new Customer();
$c2 = new Customer();

In the above example $c1 and $c2 are two objects of the Customer Class. Both these objects are allocated different blocks in the memory. Look at the diagram below:

Therefore, an object is a living instance of a class. Each object / living instance has its own memory space that can hold independent data values.

No comments:

security header validate

  HTTP Security Headers Check Tool - Security Headers Response (serpworx.com)