Chapter 03
Chapter 03
Chapter 03
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties and functions are called methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object
has all the properties and methods defined in the class, but they will have different property
values.
Objects of a class are created using the new keyword.In the example below, $apple and
$banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
In the example below, we add two more methods to class Fruit, for setting and getting the
$color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>
2. Outside the class (by directly changing the property value):
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
this keyword is used inside a class, generally within the member functions to access non-static
members of a class(variables or functions) for the current object.
<?php
class Person {
// first name of person
private $name;
?>
In the program above, we have created a private variable in the class with name $name and we
have two public methods setName() and getName() to assign a new value to $name variable
and to get its value respectively.
Whenever we want to call any variable of class from inside a member function, we use $this to
point to the current object which holds the variable.
We can also use $this to call one member function of a class inside another member function.
NOTE: If there is any static member function or variable in the class, we cannot refer it using the
$this.
$object->propertyname
$object->methodname([arg, ... ])
For example:
<?php
class <CLASS_NAME> {
// constructor
function __construct() {
// initialize the object properties
}
// destructor
function __destruct() {
// clearing the object reference
}
}
?>
Constructor can accept arguments, whereas destructors won't have any argument because a
destructor's job is to destroy the current object reference.
PHP Constructor:-Let's take the example of a class Person which has two properties, fname and
lname, for this class we will define a constructor for initialising the class properties(variables) at
the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
?>
While earlier, we were using the -> operator to set values for the variables or used the setter
methods, in case of a constructor method, we can assign values to the variables at the time of
object creation.If a class has a constructor then whenever an object of that class is created, the
constructor is called.
PHP Destructor:-PHP Destructor method is called just before PHP is about to release any object
from its memory. Generally, you can close files, clean up resources etc in the destructor
method. Let's take an example,
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// Destructor
?>
As we can see in the output above, as the PHP program ends, just before it PHP initiates the
release of the object created, and hence the destructor method is called.The destructor method
cannot accept any argument and is called just before the object is deleted, which happens
either when no reference exist for an object or when the PHP script finishes its execution.
3.3 Inheritance
<?php
class Human {
// parent class code
}
Example
<?php
class car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The car is {$this->name} and the color is {$this->color}.<br>";
}
The maruti class is inherited from the car class.This means that the maruti class can use the
public $name and $color properties as well as the public __construct() and intro() methods from
the car class because of inheritance.The maruti class also has its own method: message().
3.3.Overloading
1.Function overloading or method overloading is the ability to create multiple functions of the
same name with different implementations depending on the type of their arguments.
2.Overloading in PHP provides means to dynamically create properties and methods.
The $name argument is the name of the method being called. The $arguments argument is an
enumerated array containing the parameters passed to the $name'ed method.
<?php
class Foo {
3.3.Overriding
E.g
<?php
class aicte {
function helloWorld() {
echo "Parent"."<br>";
}
}
class msbte extends aicte {
function helloWorld() {
echo "\nChild";
}
}
$p = new aicte;
$c= new msbte;
$p->helloWorld();
$c->helloWorld();
?>
Cloning Object
1.The clone keyword is used to create a copy of an object.
2.If any of the properties was a reference to another variable or object, then only the reference
is copied.
3. Objects are always passed by reference, so if the original object has another object in its
properties, the copy will point to the same object.
4.This behavior can be changed by creating a __clone() method in the class.
<?php
class MyClass {
public $amount;
}
3.4.Introspection
Introspection is the ability of a program to examine an object characteristics such as its
name,parent class,properties and method.
Introspection allow us to:
1.Obtain the name of the class to which an object belongs as well as its member properties and
method
2.write generic debuggers,serializers,profilers
3.Introspection in PHP offers the useful ability to examine classes, interfaces, properties and
method with introspection we can write code that operates on any class or object
4.To examining classes the introspective function provided by PHP are
class_exits(),get_class_method(),get_class_vars() etc
1.class_exists():
This function is used to determine whether a class exists.It takes a string and return a boolean
value.
Syntax-$yes_no=class_exists(classname);
2.get_class_method()
<?php
if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}
?>
output:Not exist
?>
Output:
hey CO6I
"This is ves.ac.in
3.4. serialize
Syntax
serialize(value);
To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file,
a memory buffer, or transmitted across a network.
<?php
Example
// Complex array
// Convert to a string
$string = serialize($myvar);
?>
Output:
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
Unserialize()
Unserialize() Function: The unserialize() is an inbuilt function php that is used to unserialize the
given serialized array to get back to the original value of the complex array, $myvar.
Syntax:
unserialize( $serialized_array )
Below program illustrate both serialize() and unserialize() functions:
Program:
<?php
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Serialize the above data
$string = serialize($myvar);
// Unserializing the data in $string
$newvar = unserialize($string);
// Printing the unserialized data
print_r($newvar);
?>
Output:
Array
(
[0] => hello
[1] => 42