A class is user defined data type that contains attributes or data members; and methods which work on the data members.
To create a class, you need to use the keyword class followed by the name of the class.
The name of the class should be meaningful to exist within the system . The body of the class is placed between two curly brackets within which you declare class data members/variables and class methods.
<?php
class Customer {
private $first_name, $last_name;
public function customerDetails($first_name, $last_name) {
echo "Customer first name : $first_name
";
echo "Customer last name : $last_name
";
}
public function printText() {
echo "Customer text goes here";
}
}
?>
In the above program, Customer is the name of the class and $first_name/$last_name are attributes or data members. customerDetails() and printText() are methods of a class.
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.
Note :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.
<?php
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.
$this variable is a pointer to the object making the function call. $this variable is not avialable in static methods.
<?php
class Customer {
private $name;
public setName($name) {
$this->name = $name;
}
}
$c1 = new Customer();
$c2 = new Customer();
$c1->setName("Sunil");
$c2->setName("Tanmaya");
?>
In the above example, $c1 and $c2 are two separate Customer objects. Each object has its own memory to store names.But if you see the function setName() is common.During run time, how can it make a difference as to which memory location to use to store the function values. Therefore, it uses the $this variable. As mentioned earlier, $this variable is a pointer to the object making a function call.Therefore when we execute $c1->setName("Sunil"), $this in the setName() function is a pointer or a reference to the $c1 variable.
| After editing Click here: |
Output:
|
|
Hello World
|