Chapter 3.1-3.4
Chapter 3.1-3.4
Chapter 3.1-3.4
Class : A class is a template for objects. When a class is defined, it includes defining the names of its
properties and code for its methods. Encapsulation is the idea that a class provides certain methods to the
code that uses its objects, so the outside code does not directly access the data structures of those objects.
Defining 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 curly brackets.
Syntax :
<?php
class classname [extends baseclass][implements interfacename,[interfacename,…]]
{
[visibility $property [=value];…]
[function functionname(args) { code }…] // method declaration & definition
}
?>
Example :
<?php
class student
{
Properties/attributes
Methods/functions
}
?>
Using access modifiers(visibility mode), you can change the visibility of methods. Methods/properties that
are accessible outside should be declared public. Methods/properties on an instance that can only be called
by methods within the same class should be declared private. Finally, methods/properties declared as
protected can only be called from within the object’s class methods and the class methods of classes
inheriting from the class. Defining the visibility of class methods is optional; if a visibility is not specified, a
method is public.
Declaring Properties : Class member variables are called properties. Sometimes they are referred as
attributes or fields.The properties hold specific data and related with the class in which it has been
defined.Declaring a property in a class is an easy task, use one of the keyword public, protected, or private
followed by a normal variable declaration.
Example :
<?php
class student
{
public $name;
public $rollno;
}
?>
Declaring Methods :
A method is a function defined inside a class. A valid method name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.The method body enclosed within a pair of
braces which contains codes. The opening curly brace ( { ) indicates the beginning of the method code and
the closing curly ( } ) brace indicates the termination of the method.If the method is not defined by public,
protected, or private then default is public.Can access properties and methods of the current instance using
$this (Format $this->property) for non static property
Example:
<?php
class student
{
public $name;
public $rollno;
function accept($name,$rollno)
{
$this->name=$name;
$this->rollno=$rollno;
}
}
?>
Object : An object is an instance of class.The data associated with an object are called its properties. The
functions associated with an object are called its methods. Object of a class is created by using the new
keyword.
Syntax : $object = new Classname( );
Example : $s1=new student( );
Accessing properties and methods with object :
Properties and functions(methods) declared inside class with public/default visibility mode can be access
outside class using object of a the same class.
Example :
<?php
class student
{
public $name="abc"; //initialize property with default value
function display() // by default function is public
{
echo $this->name; // this is a pointer that points to calling object of function (s1)
}
}
$s1=new student(); // create new object.
echo $s1->name; // accessing property
$s1->display(); // calling method/function from class
?>
Output : abcabc
Defining and calling a method with parameters/arguments : A function can be defined that accepts
arguments. Number of arguments in function definition must be equal to number of values in call to method
/ function. Values for the arguments can be passed when the function is called along with object name.
Example :
<?php
class student
{
public $name;
function getname($name) // function defined with one argument
{
$this->name=$name;
}
function display()
{
echo $this->name;
}
}
$s1=new student();
$s1->getname("abc"); // function called with one value
$s1->display();
?>
Output : abc
The this pointer : this keyword refers to current object i.e. an object that calls a function. It is used only
inside the function/method.
3.2 Constructor and destructor:
Destructor : A destructor is the counterpart of constructor. A destructor function is called when the object is
destroyed. A destructor function cleans up any resources allocated to an object after the object is destroyed.
A destructor function is commonly called in two ways: When a script ends or manually delete an object with
the unset() function.The 'destruct' method starts with two underscores (__).
Syntax :function __destruct()
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.
Example :
<?php
class student
{
var $name;
function __construct($name)
{
$this->name=$name;
}
function __destruct()
{
echo "Destructor is executing " .$this->name;
}
}
$s1=new student("xyz");
?>
Output : Destructor is executing xyz
3.3 Inheritance ,overloading and overriding,cloning object :
Inheritance : It is the process of inheriting (sharing) properties and methods of base class in its child class.
Inheritance provides re-usability of code in a program. PHP uses extends keyword to establish relationship
between two classes.
Syntax : class derived_class_name extends base_class_name
{
Class body
}
- derived_class_name is the name of new class which is also known as child class.
- base_class_name is the name of existing class which is also known as parent class.
Example :
<?php
class college // parent/base class
{
}
class student extends college // child/derived class
{
}
?>
A derived class can inherit(share) methods of its parent class. All methods from base class and derived class
are accessed using object of derived class.
Example :
<?php
class college
{
public function displaybase() // method from base class
{
echo "Welcome to Base class";
}
}
class student extends college
{
public function displayderived() // method from derived class
{
echo "Welcome to Derived class";
}
}
$s1=new student(); // creating object of derived class
$s1->displaybase(); // call to base class method using derived class object
echo "<br><br>";
$s1->displayderived(); // call to derived class method using derived class object
?>
Output :
Welcome to Base class
A derived class can access properties of base class and also can have its own properties. Properties defined
as public in base class can be accessed inside as well as outside of the class but properties defined as
protected in base class can be accessed only inside its derived class. Private members of class can not be
inherited.
Example :
<?php
class college
{
public $name="ABC College";
protected $code=7;
}
class student extends college
{
public $sname="s-xyz";
public function display()
{
echo "College name=" .$this->name;
echo "<br>College code=" .$this->code;
echo "<br>Student name=" .$this->sname;
}
}
$s1=new student();
$s1->display();
?>
Output :
College name=ABC College
College code=7
Student name=s-xyz
Function overriding :
When a derive class redefine a method with same name from base class in its body then ,it overrides base
class method. Base and derived both classes contains same name method/function. In function overriding,
when a overridden function is called with object of derived class,it executes function from derived class only.
Example :
<?php
class college
{
function display()
{
echo "Welcome to base class";
}
}
class student extends college
{
function display()
{
echo "Welcome to derived class";
}
}
$s1=new student();
$s1->display();
?>
Output : Welcome to derived class
To access each function , create object of respective class and call the function with their objects.
The final keyword : The final keyword is used to prevent a class from being inherited and to prevent
inherited method from being overridden. While defining a class or a method if final keyword is placed
before its name then that class or method can not be inherited by its child class.
Example :
<?php
class Base
{
final function display()
{
echo "Base class function!";
}
}
class Derived extends Base
{
function display()
{
echo "Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>
Output : Fatal error: Cannot override final method Base::display()
In the above example , method display in Base class is declared with final keyword, so it will not allow
Derived class to override it i. e. redefine it in Derived class.
Example 2:
<?php
final class college
{
function display()
{
echo "Welcome to base";
}
}
class student extends college
{
function display1()
{
echo "welcome to derived";
}
}
$s1=new student();
$s1->display();
$s1->display1();
?>
Output : Fatal error: Class student may not inherit from final class (college) in C:\xampp\htdocs\oop.php on
line 17
In the above example, class base is declared with final keyword, so it can not be inherited by any child class.
Function overloading :
When a class has more than one function with same name but different number of parameters then it is
referred as function overloading. A same name function behaves differently depending on arguments /
parameters passed to it.
__call() :In PHP, for function overloading ,we have to utilize PHP's __call() method. This function is
triggered while invoking overloaded methods in the object context.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.
Example :
<?php
class Shape1 {
const PI1 = 3.142 ;
function __call($name1,$arg1){
if($name1 == 'area1')
switch(count($arg1)){
case 0 : return 0 ;
case 1 : return self::PI1 * $arg1[0] ;
case 2 : return $arg1[0] * $arg1[1];
}
}
}
$circle1 = new Shape1();
echo "Area of Circle= ".$circle1->area1(3);
echo "<br><br>";
$rect1 = new Shape1();
echo "Area of Rectangle= ".$rect1->area1(8,6);?>
Output :
Area of Circle= 9.426
Area of Rectangle= 48
Cloning object :
Cloning object is creating a copy of existing object. An object copy is created by using the clone keyword. If
any of the properties was a reference to another variable or object, then only the reference is copied. 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.
Syntax : $newobject = clone $existingobject;
Example :
<?php
class student
{
function getdata($nm,$rn)
{
$this->name=$nm;
$this->rollno=$rn;
}
function display()
{
echo "<br>name = ".$this->name;
echo "<Br>rollno = ".$this->rollno;
}
}
$s1 = new student();
$s1->getdata("rutuja",1);
$s1->display();
$s2 = clone $s1;
echo "<br> Cloned object data ";
$s2->display();
?>
Output :
name = rutuja
rollno = 1
Cloned object data
name = rutuja
rollno = 1
Example 2:
<?php
class MyClass {
public $amount;
}
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
$copy = clone $obj;
$obj->amount = 6;
print_r($copy);
?>
Output :
MyClass Object ( [amount] => 5 ) MyClass Object ( [amount] => 6 )
Note :-
The print and echo are both language constructs to display strings. The echo has a void return type,
whereas print has a return value of 1 so it can be used in expressions. The print_r is used to display human-
readable information about a variable.
Examining Classes : To determine whether a class exists, class_exists() function is used that accepts a
string as a argument and returns a Boolean value.
Retrieving methods : Class methods declared in a class can be retrieved using get_class methods( )
function. This function accepts a class name as an argument and return an array consisting of methods
defined in the class.
Syntax : $methods=get_class_methods(‘classname’);
Example Code :
<?php
class student
{
function display()
{
echo "Hello";
}
function show()
{
echo "Hi";
}
}
$method=get_class_methods('student');
foreach ($method as $val)
{
echo $val."<Br>";
}
?>
Output:
display
show
<?php
class college
{
public $cname;
public $ccode;
}
class student extends college
{
public $name;
public $rollno;
}
$property=get_class_vars('student');
foreach ($property as $key=>$val)
{
echo "{$key} <Br>";
}
?>
Output :
name
rollno
cname
ccode
Finding parent class : To find parent class of any child class get_parent_class( ) function is use. This
function accepts child class name as an argument and returns name of its parent class. It may accept object
name also.
Syntax : $superclass = get_parent_class(childclassname);
Example :
<?php
class college
{
}
class student extends college
{
}
$parentclass=get_parent_class('student');
echo $parentclass;
?>
Output : college
Examining an Object : To make sure that a specified variable is an object of a class , use is_object( )
function. It accepts variable name as an argument and returns (1) true if it is an object or (0) false if it not a
object.
Syntax : $result = is_object($var);
Example :
<?php
class college
{
}
$c=new college();
echo is_object($c);
?>
Output : 1
Finding class of an object : By using get_class( ) function , one can find name of the class to which an
object belongs to. This function accepts name of the object as an argument and returns name of the class to
which it belongs to.
Syntax : $classname = get_class(object);
Example :
<?php
class college
{
}
$c=new college();
echo get_class($c);
?>
Output : college
Examining method existence : Before calling a method on an object, one can ensure that it exists
using the method_exists() function. This function accepts object name and method name as arguments and
return 1(true) if method exist or 0(false) if it does not exists.
Syntax : $methodExists = method_exists(object, ‘method’);
Example :
<?php
class college
{
function display()
{
echo "Hi";
}
}
$c=new college();
$a=method_exists($c,'display1');
if($a==1)
echo "Method Exist";
else
echo "Method does not exists";
?>
Output : Method does not exists
unserialize ( ) : - This function is used to convert serialized data back into actual data. It accepts
serialized string and returns an array of values.
Syntax : unserialize(string);
- string is a serialized value
Example :
<?php
$data = serialize(array("Red", "Green", "Blue"));
echo $data . "<br>";
$test = unserialize($data);
var_dump($test);
?>
Output :
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}
array(3) { [0]=> string(3) "Red" [1]=> string(5) "Green" [2]=> string(4) "Blue" }
⚫ One practical consequence of this is that if you use PHP sessions to automatically serialize and
unserialize objects, you must include the file containing the object’s class definition in every page on
your site. For example, your pages might start like this:
<?php
include "object_definitions.php"; // load object definitions
session_start(); // load persistent variables
?>
PHP may include two functions for objects during the serialization and unserialization process:
The __sleep() method is called on an object just before serialization; it can perform any cleanup necessary
to preserve the object’s state, such as closing database connections, writing out unsaved persistent data, and
so on. It should return an array containing the names of the data members that need to be written into the
bytestream. If you return an empty array, no data is written.
the __wakeup() method is called on an object immediately after an object is created from a bytestream. The
method can take any action it requires, such as reopening database connections and other initialization tasks.