Professional Documents
Culture Documents
Oops Consepts in PHP How To Create A Class
Oops Consepts in PHP How To Create A Class
Definition of a Class
A class is user defined data type that contains attributes or data members;
and methods which work on the data members. (You will learn more about
data members and methods in following tutorials. This tutorial focuses only on
learning how to create a Class in PHP5)
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 (See note on naming a class towards the end of the article). The body
of the class is placed between two curly brackets within which you declare
class data members/variables and class methods.
Following is a prototype of a PHP5 class structure
class <class-name> {
On the basis of the above prototype, look below an example of PHP5 class
Example of a Class:
class Customer {
private $first_name, $last_name;
Note:
You can read more about private, public and protected in this tutorial on Access
Specifiers
Naming Conventions
Naming Convention for Class:
As a general Object Oriented Programming practice, it is better to name the
class as the name of the real world entity rather than giving it a fictitious name.
For example, to represent a customer in your OOAD model; you should name
the class as Customer instead of Person or something else.
Naming Conventions for Methods:
The same rule applies for class methods. The name of the method should tell
you what action or functionality it will perform. E.g. getData() tells you that it
will accept some data as input and printData() tells you that it will printData().
So ask yourself what you would name a method which stores data in the
database. If you said storeDataInDB() you were right.
Look at the manner in which the method storeDataInDB() has been named. The
first character of the first word of the method is lower case i.e. ‘s‘tore. For rest
of the words in the function viz Data/In/DB have been named as first character
Uppercase and the remaining characters of the words as lower case i.e. ‘D’ata
‘I’n ‘D’B. Therefore it becomes storeDataInDB()
Naming Convention for Attributes:
Attributes of a class should be named on the basis of the data that they hold.
You should always give meaningful names to your attributes. For attributes you
should split the words with an underscore (_) i.e. $first_name, $last_name, etc.
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 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:
Let’s take a problem statement and define a PHP5 Class for it.
Problem Statement:
Define a class to encapsulate Student. The data required to be captured is
Student’s first name, last name, date of birth, address and telephone number.
Solution:
class Student {
public $first_name;
public $last_name;
public $date_of_birth;
public $address;
public $telephone;
}
Objects as Attributes
In addition to declaring attributes as intrinsic data types (int, string, etc), you
can also declare data members as objects of another class. This is called
aggregation in Object Oriented Analysis and Design (OOAD). Lets look at an
example below:
class Customer {
private $first_name, $last_name;
private $outstanding_amount = 0; //example of default value
class Order {
private $order_id;
private $customer;
The reason why you require methods is so that you can perform necessary
validations on the data passed. Let’s re-look at the above example with
necessary validation code.
class Customer {
private $name;
public function setName($name) {
if(trim($name) != "") {
$this->name = $name;
return true;
}
else {
return false;
}
}
}
Accessor Methods:
Accessor methods are also know as getter methods. The reason why we need
an accessor method is to be able to read the value of a property/attribute in a
class object. In real OOAD practice most of the data members that you define
would either be private or protected (more on this will be covered in the tutorial
on Access specifiers), therefore to access data of such data members that have
been defined as either private or protected will require an implementation of
accessor or getter methods.
Note: To make a property or data member as non-read only; you
should not provide a getter or accessor method.
Mutator Methods:
Mutator methods are opposite to accessor methods. Mutator methods provides
a mechanism to store data in data members that have either been declared as
private or protected. The reason why you should provide a mutator method is
to provide necessary validation on the data that is to be stored in the data
member of the class.
Note: To make a property or data member as read only; you should
not provide a setter or mutator method.
//mutator method
public function setName($name) {
if(trim($name) != "") {
$this->name = $name;
return true;
}
else {
return false;
}
}
//accessor method
public getName() {
return $this->name;
}
}
Output:
Sunil Bhatia
In the above example the setName() method accepts a customer’s
name and validates to check if $name is blank. If $name is blank the
setName() function returns false; otherwise it stores the $name in the
$this->name of the class and returns true. The getName() returns the
name stored in the $name data member of the $c1 object.
Definition of a Constructor
A constructor is a special function of a class that is automatically executed
whenever an object of a class gets instantiated.
What does this all mean?
Lets revisit that definition in more simple terms. A constructor is a special
function - this means that a constructor is a function; but its special. But, why is
it special? It’s special because it is automatically executed or called when an
object of a class is created.
Why do we need a Constructor?
It is needed as it provides an opportunity for doing necessary setup operations
like initializing class variables, opening database connections or socket
connections, etc. In simple terms, it is needed to setup the object before it can
be used.
PHP5 Constructor
In PHP5 a constructor is defined by implementing the __construct() method.
This naming style has been introduced in PHP5. In PHP4, the name of the
constructor was the same name as that of the class. So, for example if you had
a class Customer, you would have to implement a function Customer().
PHP5 to be backward complaint also supports the PHP4 rule. When an object is
created, PHP5 searches for __construct() first. If __construct() is not defined it
then searches for a method with the same that of the class. However, if you
define both; PHP5 will first search for __construct() method and execute it if
available, otherwise it will execute the same class name function.
Let’s look at how to define a PHP5 Constructor
class Customer {
public function __construct() {
//code
}
}
In the above example on line number 24, we create a new object $c1
and pass values “Sunil”, “Bhatia” and zero to the constructor defined
on line number starting 7. The constructor now takes 3 arguments
and stores them in the internal private variable $first_name,
$last_name and $outstanding_amount respectively.
Definition of a Destructor
A destructor is a special function of a class that is automatically executed
whenever an object of a class is destroyed.
What does this all mean?
Let’s revisit that definition in more simple terms. A destructor is a special
function - this means that a destructor is a function; but its special. But, why is
it special? It’s special because it is automatically executed or called when an
object of a class is destroyed. An object of a class is destroyed when
1. it goes out of scope,
2. when you specifically set it to null,
3. when you unset it or when the program execution is over.
In the next PHP5 tutorial you will learn about Access Specifier
PHP Class Access Specifier:
In the earlier tutorials we have witnessed keywords like public, private and
protected. These are nothing but access specifiers. So, lets understand what
access specifiers are.
Definition of Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other
class objects, external functions and global level code) have on the class
methods and class data members. Access specifiers can either be public,
private or protected.
Why do we need Access specifiers
Access specifiers are used as a key component of Encapsulation and Data
Hiding. By using either of the access specifiers mentioned above i.e. public,
private or protected you can hide or show the internals of your class to the
outside world.
Explanation of each access specifier
1. Private
2. Protected
3. Public
1. Private
A private access specifier is used to hide the data member or member function
to the outside world. This means that only the class that defines such data
member and member functions have access them. Look at the example below:
class Customer {
private $name;
$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; //error, $name cannot be accessed from outside the class
//$name can only be accessed from within the class
echo $c->getName(); //this works, as the methods of the class have access
//to the private data members or methods
$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; // this will work as it is public.
$c->name = "New Name" ; // this does not give an error.
3. Protected
A protected access specifier is mainly used with inheritance. A data member or
member function declared as protected will be accessed by its class and its
base class but not from the outside world (i.e. rest of the script). We can also
say that a protected data member is public for the class that declares it and it’s
child class; but is private for the rest of the program (outside world). Look at
the example below:
class Customer {
protected $name;
private $discount;
$this->discount = $discount;
}
}
$dc = new DiscountCustomer();
$dc->setData("Sunil Bhatia",10);
echo $dc->name; // this does not work as $name is protected and hence
// only available in Customer and DiscountCustomer class
In the above example, echo $dc->name will not work work $name has
been defined as a protected variable and hence it is only available in
Customer and DiscountCustomer class.
You will learn more about inheritance later in this tutorial series. You should
revisit this tutorial and read more on the protected section again when you
understand inheritance better.
Important Note of Access Specifier in PHP5
In PHP5, access specifiers are public by default. This means that if you don’t
specify an access specifier for a data member or method then the default
‘public’ is applicable
----------------------------------------------------------------------------------
------------------------------
$this Variable Explained
$this variable is a pointer to the object making the function call. $this variable
is not avialable in static methods. We will learn more about static methods in
the next series of tutorials.
Example:
class Customer {
private $name;
public setName($name) {
$this->name = $name;
}
$c1->setName(“Sunil”);
$c2->setName(“Vishal”);
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.
You can also use instanceOf operator to compare an object with the name of
the class, look at the example below:
class Person {
...
}
In PHP4 the only constants that we would declare were global constants. In
PHP5 it is possible to define a class level constant. These constants are specific
to the class and hence don’t clutter the global level constant space.
The next logical question is if we can create an object of the Customer class
and using the scope resolution operator access the constant. The answer is no;
reason - because a constant belongs to the class definition scope and not to an
object.
Example of accessing Constants within a function
class Customer {
const TYPES = "Anything";
$c = new Customer();
$c->showConstant();
Output:
Echo from showConstant() : Anything
Some observations on Constants
1. Variables defined as constants cannot be changed.
2. Only a string or numeric value can be assigned to a constant.
3. Arrays, Objects & Expressions cannot be assigned to a constant.
4. A class constant can only be accessed via the scope resolution operator
(::) executed on the class name.
5. A class constant cannot have <a>access specifiers</a> assigned to it
(private, public & protected)
Static data members and methods:
In this tutorial you will learn all about static data members and methods
• Meaning of static data members
• Meaning of static methods
• Defining static data members in PHP5
• Defining static methods in PHP5
• Accessing static data members in PHP5
• Accessing static methods in PHP5
• Rules to keep in mind for static methods
class Customer {
class Customer {
class Customer {
echo Customer::$instance_count;
Output:
2
In the above example, $instance_count is a static data member. Every
time a new object is created the constructor is executed and the
$instance_count variable is incremented by one. To echo the value
contained in $instance_count variable, we use the :: (scope
resolution) operator.
Accessing static method in PHP5
A static method can be accessed using the name of the class along with the
scope resolution operator (::) i.e. you don’t need to create an instance of that
class. However, you can also access it with an instance variable.
Look at the example below:
class Customer {
Output:
2
2
$c = new DerivedClass();
$c->myMethod();
class BaseClass {
final public function myMethod() {
echo "BaseClass method called";
}
}
$c = new DerivedClass();
$c->myMethod();
What is an exception?
An exception is a logical/system error that occurs during the normal execution
of a script. The exception could either be raised by the system or the program
itself it the exception cannot be handled and the caller script/function needs to
be informed about the same.
try {
check();
}
catch(Exception $e) {
echo "Message : " . $e->getMessage();
echo "Code : " . $e->getCode();
}
function check() {
if(some error condition) {
throw new Exception("Error String",Error Code);
}
}
In the above example, the method check() is called between the try
{} block. The try{} block is the area where you will place your code
that could raise an exception. Below the try{} block is the catch() {}
block. The catch block expects the Exception type of object as a
parameter. Within the catch() {} block you will place your logic to
either fix the issue or log the error.
class Exception {
protected $message;
protected $code;
protected $file;
protected $line;
private $string;
private $trace;
Related Reading:
parent::__construct($t_message, $code);
function testException() {
try {
testException();
}
catch(CustomerException $e) {
echo "Error Message : " $e->getMessage();
echo "Error Code : " $e->getCode();
}
Output:
Error Message : CustomerException has been raised
Error Code : 101
Inheritance:
In the tutorial we will understand what is Inheritance in general and how to
inherit classes in PHP5.
Definition of Inheritance:
Inheritance is the mechanism of deriving a new class from an existing class. It
allows a sub-class / child class to share/inherit the attributes and behaviors of a
base-class or parent class. These inherited attributes and behaviors are usually
modified by means of extension.
PHP5 Inheritance
To inherit in PHP5, you should use the keyword ‘extends’ in the class definition.
In PHP5 only single inheritance is allowed. Look at the example below:
class Person {
private $name;
private $address;
public getCustomerId() {
return $this->customer_id;
}
public getCustomerName() {
return $this->getName();// getName() is in Person
}
}
In the above example, class Customer extends from the Person class.
This means that Customer class is the child class and the Person base
class. The child class Customer extends the method getName() and
calls it in the getCustomerName() method of the Customer class.
$c = new Customer("Sunil","28");
echo "Name : " . $c->name; //causes an error
$c = new Customer("Sunil","28");
echo "Age : " . $c->age; //prints 28
3. protected
A protected access specifier allows the derived class to access the data
member or member functions of the base class, whereas disallows global
access to other objects and functions.
class Person {
protected $name;
}
$c1->name = “Sunil”;
$e = new Eagle();
$s = new Swift();
$e->fly();
echo "\n";
$s->fly();
Output:
Fly method of the Eagle Class called
Fly method of the Swift Class called
In the above example, we create two objects of class Eagle and Swift.
Each of these classes have overridden the method fly() and have
provided their own implementation of the fly() method that has been
extended from the Bird class. The manner in which they have been
extended the Bird class fly() method is not called as both these
classes have provided a new functionality for the fly() method.
$c1->calculateAge("something");
$p1->calculateAge("something More");
Output:
calculateAge called of Customer Class
calculateAge called of Person Class
PHP5 Inheritance - Invoking parent methods
When you override a method of the base class, it’s functionality is completely
hidden unless it has been explicitly invoked from the child class. To invoke a
parent class method you should use the keyword parent followed by the scope
resolution operator followed by the name of the method as mentioned below:
parent::function_name();
$c = new Customer();
$c->showData();
Output:
This is Person’s showData()
This is Customer’s showData()
In the above example, look at the way in which the showData()
function in the Customer child class is invoking the the Person parent
class’s showData() function. When the program executes the
showData() method if the Customer class is called which inturn calls
the showData() function of the parent class. After the parent class’s
showData() function complets its execution the remaining code in
showData() function of the Customer class is executed.
$c = new Customer();
Output:
This is Person’s __construct()
This is Customer’s __construct()
This is Person’s __destruct()
This is Customer’s __destruct()
private $price;
What is an Interface?
An interface is a contract between unrelated objects to perform a common
function. An interface enables you to specify that an object is capable of
performing a certain function, but it does not necessarily tell you how the
object does so, this means that it leaves for classes implementing an interface
to define its behaviour.
To extend from an Interface, keyword implements is used.
We can have a class extend from more than one Interface.
interface Storable {
function getContentsAsText();
}
class Indexer {
public function readAndIndex(Storable $s) {
$textData = $s->getContentsAsText();
//do necessary logic to index
echo $textData;
}
}
$p = new Document();
$i = new Indexer();
$i->readAndIndex($p);
In the above example, Document and the Indexer class are two
independant classes. The Indexer class is designed to index the
contents of any text. Using the Storable interface above, we declare a
method getContentsAsText() in the Document class. Because the
Indexer class is only concerned with the TEXT, hence we can call
getContentsAsText() method on the object of Document. This way any
class if it implements the method getContentsAsText() can get
indexed
Polymorphism:
Meaning of Polymorphism
Polymorphism is derived from two Greek words. Poly (meaning many) and
morph (meaning forms). Polymorphism means many forms. In C you have two
methods with the same name that have different function signatures and
hence by passing the correct function signature you can invoke the correct
method.
This is how polymorphism is achieved in languages like C where in a function
sum(int, int) differs from sum(float, float). Therefore the method sum() has
many forms depending on the parameters being passed to it.
The meaning with Object Oriented languages changes. With Object Oriented
language polymorphism happens:
When the decision to invoke a function call is made by inspecting the object at
runtime it is called Polymorphism
Why method polymorphism cannot be achieved
The reason why polymorphism for methods is not possible in PHP is because
you can have a method that accepts two parameters and call it by passing
three parameters. This is because PHP is not strict and contains methods like
func_num_args() and func_get_arg() to find the number of arguments passed
and get a particular parameter.
Because PHP is not type strict and allows variable arguments, this is why
method polymorphism is not possible.
PHP 5 Polymorphism
Since PHP 5 introduces the concept of Type Hinting, polymorphism is possible
with class methods. The basis of polymorphism is Inheritance and overridden
methods.
Lets look at an example:
class BaseClass {
public function myMethod() {
echo "BaseClass method called";
}
}
$c = new DerivedClass();
processClass($c);
class Customer {
private $firstName, $lastName, $email;
$c = new Customer(”Sunil”,”Bhatia”,”email@domain.com”);
?>
Output:
Customer Object is >> Debug message from Customer Class : First
Name = Sunil, Last Name = Bhatia, Email = email@domain.com
See how in this example $c Customer Object got converted into a string type
when used with the dot (.) concatenation operator. In the background the
magic method __toString() is automatically called when such a conversion
happens.
Security Tip:
Be careful not to include sensitive data as part of the output as you could
compromise security by leaking secure information. Many applications are
written to write object states in a log file, therefore you should ensure that
sensitive information like Credit Card information, etc is not made available
through the magic method __toString()
Subscribe to my newsletter and be informed as a new PHP5 tutorial is posted
online:
This article talks about the use of __get() (double underscore - get()) and
__set() (double underscore - set()) PHP5 OOPS magic methods.
By default PHP is a Loosely typed language and therefore it is not necessary to
declare variables before using them. This also holds true for using class
members. Look at an example below.
<?php
class Customer {
public $name;
}
$c = new Customer();
$c->name = “Sunil”; // $name is set because its public
?>
Ideally in a strict language this would have been an error. But, with PHP this
works perfectly well as you can assign values to an undefined variable.
Because of the above limitation, PHP engine provides two magic methods
__get() and __set(). __get() is used when value from an undefined variable is
to be read and __set() is used when a value is to be assigned to a undefined
variable of a class.
__set() allows you to provide functionality to validate data being stored. See
example below:
<?php
class Customer {
public $name;
private $data = array();
$c = new Customer();
$c->name = “Sunil”; // $name is set because its public
echo $c->email;
?>
The next step is to store these values into the $data array so that you could
retrieve it later.
The __get() method works in the similar fashion. When you echo $c->email,
__get() method is called and the name email is passed in the $dt of the __get()
method.
Tip:
It is possible to stop this behavior of PHP to assign values to undefined issues.
The solution is that you raise an exception from within __set() method. Look at
the code below:
<?
class Customer {
private $name;
$c = new Customer();
$c->email = “email@domain.com”; //this will cause an exception to
be raised
?>
These methods are automatically called internally when isset() and unset() is
called on undeclared data members. The magic method __isset() method
receives an argument - the value of which is the name of the variable that the
program wants to test if the variable is set or not.
The magic method __unset() method receives an argument - the value of
which is the name of the variable that the program wants to unset.
Look at the example below:
class Customer {
private $data = array();
$c = new Customer();
$c->name = “Sunil Bhatia”;
echo isset($c->name).”\n”;
echo unset($c->name);
In the example above the script creates a new Customer Object. The
program assigns a string value to an undeclared variable i.e. $c-
>name. The undeclared variable is handled by the magic method
__set(). Read this post on PHP5 Magic Methods __set() if you need
more understanding how the magic method __set() works.
Similarly, when the program calls unset() on the undeclared variable i.e. $c-
>name, the PHP5 magic method __unset() is invoked that takes the name of
the undeclared variable i.e. ‘name’ and unsets the internal array
$data[’name’].
_call() Method:
This tutorial will teach you how and when to use the magic method __call().
The magic method __call() is to undeclared methods what __get() and __set()
are to undeclared data member.
These methods are automatically called internally when the program tires to
execute a method that has not been defined within the class at the time of
development.
The magic method __call() takes two arguments. The first argument is the
name of the undeclared method invoked by the program and the second is an
array that contains a list of parameters passed to the undeclared array.
$c = new Customer();
$c->setName("Sunil","Bhatia");
Output:
string(7) “setName”
array(2) {
[0]=>
string(5) “Sunil”
[1]=>
string(6) “Bhatia”
}
Using this method, you can provide code to handle calls to undeclared method.
To disallow programs to call an undeclared method, you should raise an
exception from within __call() magic method.
Look at the example below:
class Customer {
$c = new Customer();
$c->setName("Sunil","Bhatia");
Output:
Fatal error: Uncaught exception ‘Exception’ with message ‘Undeclared method
execution not allowed’ in D:sunilbwebsiteprogsmagic_call.php:6
Stack trace:
#0 [internal function]: Customer->__call(’setName’, Array)
#1 D:sunilbwebsiteprogsmagic_call.php(11): Customer->setName(’Sunil’,
‘Bhatia’)
#2 {main}
thrown in D:sunilbwebsiteprogsmagic_call.php on line 6
In the above program, when the script calls an undeclared variable $c-
>setName(), the magic method __call() is executed. On executing the magic
method __call(), an exception is raised and the execution of the program
stops there (unless we use the try..catch statements)
_autoload():
This tutorial will teach you how and when to use the magic method
__autoload().
The magic method __autoload() function is a convenience that allows you to
use classes without having to explicitly write code to include them.
The magic method __autoload() is not included in your class definition as this
is to be called once in a script. The best place to put the autoload() file is in
your configuration file which is loaded in all your other scripts.
$c = new Customer();
But this causes performance issues. Each time the above script is executed,
orders.php is included. To avoid this performance hit, we would have to do
additional programming to ensure that the file orders.php is loaded only when
needed.
This is the reason why magic method __autoload() should be used. Look at
the example below:
function __autoload($class) {
require $class . '.php'; //is substituted as require Customer.php (with capital 'C')
}
$c = new Customer();
Therefore, on the line when an instance of the customer class is created i.e.
object $c, magic method __autoload() is called with the parameter $class
containing value ‘Customer’. Within the __autoload() method we call the
‘require’ method. The require method tries to load $class.’php’ file i.e.
Customer.php. Therefore, as stated earlier, the __autoload() method has its
beneficial side effect of requiring strict file naming convention.
The __autoload() method is called only once for each new class that needs to
be loaded. Subsequent instantiation of the Customer class object will not call
the __autoload() method again. Therefore, this offers performance
improvements in your scripts because, unless the class is needed - files are not
loaded. Therefore, the PHP engine does not have to parse and compile an
unnecessary file.
Please feel free to leave behind any comments or questions that you might
have.
_sleep() and _wakeup()
The magic method __sleep() and __wakeup() is called when an object is
serialized. The magic method __sleep() and __wakeup() provides a method to
clean up and restore objects before being serialized.
Working with the magic method __sleep()
__sleep() magic method is called when the object of a class is about to be
serialized. This magic method __sleep() does not accept any parameter and
returns an array. The array should contain a list of class members that should
be serialized. This means that if you don’t wish to serialize a particular class
member, you should not include it in the array. Look at the example below:
class Customer {
private $name;
private $credit_card_number;
public function setName($name) {
$this->name = $name;
}
$c = new Customer();
$c->setName("Sunil");
$c->setCC("1234567890123456");
$data = serialize($c)."\n";
echo $data."\n";
Output:
O:8:”Customer”:1:{s:14:” Customer name”;s:5:”Sunil”;}
In the above example, you can see that the serialized string data only
contains the name of the Customer Object. This is because the
__sleep() magic method returned an array containing only the
‘name’ data member.
$c = new Customer();
$c->setName("Sunil");
$c->setCC("1234567890123456");
$data = serialize($c)."\n";
var_dump(unserialize($data));
Output:
object(Customer)#2 (2) {
[”name:private”]=>
string(5) “Sunil”
[”credit_card_number:private”]=>
string(16) “1234567890123456″
}
In the above example, you can see that after the $c object has been
serialized and the output stored in $data variable, we use the $data
variable and pass it to the unserialize(). Before the object is
unserizlied and object created, the __wakeup() method is called. In
the __wakeup() method you should ideally make a database call to
fetch data of the missing member variable.
Please feel free to leave behind any comments or questions that you might
have.
_clone method():
Before I begin to explain the use of a __clone() method, lets try and understand
what does object cloning mean.
To clone an object means to create a duplicate of an object. With regular
variables $a = $b means that a new variable $a gets created that contains the
value of $b. This means that 2 variables get created.
With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 gets
created. When we execute $obj2 = $obj1, the reference of $obj1 is assigned to
$obj2. This means that $obj1 and $obj2 point to the same memory space. Look
at the diagram below.
Lets look at an example where only references are assigned to another object:
class Customer {
private $name;
$c2->setName("Vishal");
echo $c1->getName()."\n";
echo $c2->getName()."\n";
Output:
Vishal
Vishal
In the above example, $c2 has the reference of $c1; therefore, when
you set a new name in the $c2 object - $c1 object changes as well.
Therefore, when an object is assigned as a reference; changes made
to one object are also reflected in the other.
After the above line is executed $obj2 with a new memory space is created
with the data members having the same value as that of $obj1. This is also
referred to as shallow copy.
The above technique works with a class having data members that
are of intrinsic type i.e. int, boolean, string, float, etc.. However, this
technique will not work with a class that has a data member which is
an object of another class. In such a scenario, the cloned object
continues to share the reference of the data member object of the
class that was cloned.
So, how do we resolve this issue? Doing a regular shallow copy won’t help us.
To allow aggregated objects (i.e. data members that are objects of another
class) to also get cloned properly we need to use the concept of ‘deep copy‘
as opposed to ‘shallow copy‘. To implement a ‘deep copy‘ you should
implement the magic method __clone().
You could also provide the implementation of __clone() magic method even
when you don’t have an aggregated object. You would want to do this for
providing necessary clean up operations, conversions or validations.
Lets explore a very simple example of cloning intrinsic data types:
class Customer {
private $name;
$c2->setName("Vishal");
echo $c1->getName()."\n";
echo $c2->getName()."\n";
Output:
Sunil
Vishal
In the above example, observe the line where the statement $c2 =
clone $c1 is executed. This is internally represented as $c2 =
$c1.__clone(). However, you cannot explicitly call the __clone()
method on an object as the __clone() is automatically called. Now that
$c1 and $c2 are two individual objects, changes made to one object is
not reflected in the other.
Cloning aggregate objects (i.e. data members that are objects of
another class)
To clone a class having aggregated objects, you should perform ‘deep copy‘.
Please refer to the example below:
class Order {
private $order_id;
private $customer;
$o = new Order();
$o->setOrderId($this->order_id);
class Customer {
private $name;
$c = new Customer();
$c->setName("Sunil");
$o1 = new Order();
$o1->setOrderId("OD0001");
$o1->setCustomer($c);
$o2->getCustomer()->setName("Vishal");
var_dump($c);
var_dump($o1);
var_dump($o2);
Output:
object(Customer)#1 (1) {
[”name:private”]=>
string(5) “Sunil”
}
object(Order)#2 (2) {
[”order_id:private”]=>
string(6) “OD0001″
[”customer:private”]=>
object(Customer)#3 (1) {
[”name:private”]=>
string(5) “Sunil”
}
}
object(Order)#4 (2) {
[”order_id:private”]=>
string(6) “OD0001″
[”customer:private”]=>
object(Customer)#6 (1) {
[”name:private”]=>
string(6) “Vishal”
}
}
In the above example both $o1 and $o2 have their own set of
customer objects, therefore changes made to one object is not
reflected in another. This example implements the concepts of ‘deep
copy‘.
I hope this tutorial was helpful. Please feel free to leave behind any comments
or questions that you might have.