Attachment
Attachment
PHP
Day 3.1:
We can imagine our universe made of different objects like sun, earth, moon etc.
Similarly we can imagine our car made of different objects like wheel, steering, gear etc.
Same way there is object oriented programming concepts which assume everything as
an object and implement a software using different objects.
What is OOPS?
Object-Oriented Programming or simply OOPs is a programming approach or paradigm
that gives its prime consideration to the data and its associated functions. It uses the
concept of wrapping up the data as an object-entity having its associated properties, to
provide higher security and less exposure to the data. As nothing is more important than
the data itself, this approach is highly in use and widely accepted by programmers
worldwide. The programming languages that do not support OOPs methodologies and
their concepts are slowly getting deprecated, and the languages that are now being
developed, support OOPs and are the extended version of object-oriented
programming.
To relate programming with the real world, this methodology considers everything in the
world as an entity or an object, and every object has some of its attributes or properties.
So, the concept of the classes and objects can be applied to model an entire
application. The overall development of an application in an object-oriented perspective
can be summarized as:
Reusability
OOP allows you to create reusable code by encapsulating functionality within classes.
Once a class is defined, you can create multiple instances (objects) of that class,
making it easy to reuse the code across different parts of your application. Code reuse
not only saves development time but also enhances consistency and reduces the
likelihood of errors.
Modularity
OOP promotes a modular approach to software development. You can break down your
application into smaller, manageable modules or classes. Each class represents a
specific entity or functionality, making it easier to understand, maintain, and update.
Flexibility
OOP provides flexibility in design and implementation. With features like inheritance and
polymorphism, you can create a hierarchy of classes, allowing for the extension and
modification of existing code without altering its core functionality.
Maintainability
OOP promotes code organization and structure, making it easier to understand and
maintain. Classes encapsulate data and behavior, providing a clear separation of
concerns.
Changes to one part of the codebase are less likely to affect other parts if the code is
well-designed using OOP principles. This isolation makes it easier to debug, update,
and enhance the application over time.
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...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color)
and two methods set_name() and get_name() for setting and getting the $name
property:
<?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.
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;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
<?php
class Fruits
{
public $name; // Data members or variable
public $color; // Data members or variable
$f1->setName("Apple");
$f1->setColor("Red");
$val = $f1->getName();
echo $val;
echo $f1->getColor();
print $f2->getName();
print $f2->getColor();
?>
Web Based Application Development with
PHP
Day 3.2:
The $this keyword refers to the current object, and is only available inside methods.
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 {
private $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
Example:
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
Properties and methods can have access modifiers which control where they can be
accessed.
In the following example we have added three different access modifiers to three
properties (name, color, and weight). Here, if you try to set the name property it will work
fine (because the name property is public, and can be accessed from everywhere).
However, if you try to set the color or weight property it will result in a fatal error
(because the color and weight property are protected and private):
Example:
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
In the next example we have added access modifiers to two functions. Here, if you try to
call the set_color() or the set_weight() function it will result in a fatal error (because the
two functions are considered protected and private), even if all the properties are public:
<?php
class Fruit {
public $name;
public $color;
public $weight;
function set_name($n) { // a public function (default)
$this->name = $n;
}
protected function set_color($n) { // a protected function
$this->color = $n;
}
private function set_weight($n) { // a private function
$this->weight = $n;
}
}
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
Difference between self and $this:
The keyword self is used to refer to the current class itself within the scope of that class
only whereas, $this is used to refer to the member variables and function for a particular
instance of a class.
PHP self operator: The self operator represents the current class and thus is used to
access class variables or static variables because these members belong to a class
rather than the object of that class.
Syntax:
self::$static_member
PHP $this operator: The $this, as the ‘$’ sign suggests, is an object. $ This represents
the current object of a class. It is used to access non-static members of a class.
Syntax:
$this->$non_static_member;
Example:
<?php
class StudentDetail{
public $name;
public static $age;
public function getName() {
return $this->name;
}
public static function getAge() {
return self::$age;
}
public function getStudentAge() {
return self::getAge();
}
}
$obj = new StudentDetail();
$obj->name = "Python";
StudentDetail::$age = "18";
echo "Name : " .$obj->getName()."\xA";
echo "Age : " .StudentDetail::getStudentAge();
?>
self $this
Self keyword refers to the class $this could refer to the member
members, but doesn’t point toward variables and function for a
any particular object of the class. selected instance of the class.
Constructors are special member functions for initial settings of newly created object
instances from a class, which is the key part of the object-oriented concept in PHP5.
Constructors are the very basic building blocks that define the future object and its
nature. You can say that the Constructors are the blueprints for object creation providing
values for member functions and member variables.
Once the object is initialized, the constructor is automatically called. Destructors are for
destroying objects and automatically called at the end of execution.
In this article, we are going to learn about object-oriented concepts of constructors and
destructors.
Both are special member functions of any class with different concepts but the same
name except destructors are preceded by a ~ Tilda operator.
__construct():
function __construct()
{
// initialize the object and its properties by assigning
//values
}
__destruct():
function __destruct()
{
// destroying the object or clean up resources here
}
Note: The constructor is defined in the public section of the Class. Even the values to
properties of the class are set by Constructors.
Constructor types:
● Default Constructor:It has no parameters, but the values to the default
constructor can be passed dynamically.
● Parameterized Constructor: It takes the parameters, and also you can pass
different values to the data members.
● Copy Constructor: It accepts the address of the other objects as a parameter.
Example:
<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class Tree";
}
function __construct()
{
echo "Its a Pre-defined Constructor of the class Tree";
}
}
$obj= new Tree();
?>
Example:
<?php
class Employee
{
Public $name;
Public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->position=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->position."\n";
}
}
$employee_obj= new Employee("Rakesh","developer");
$employee_obj->show_details();
$employee2= new Employee("Vikas","Manager");
$employee2->show_details();
?>
Constructors start with two underscores and generally look like normal PHP functions.
Sometimes these constructors are called as magic functions starting with two
underscores and with some extra functionality than normal methods. After creating an
object of some class that includes constructor, the content of constructor will be
automatically executed.
Note: If the PHP Class has a constructor, then at the time of object creation, the
constructor of the class is called. The constructors have no Return Type, so they do not
return anything not even void.
A Copy Constructor in PHP is a special constructor method that creates a new object by
copying an existing object. Since PHP does not have a built-in copy constructor like
C++, you need to define one manually.
PHP provides the __clone magic method, which can also be used to create a deep copy
of an object.
<?php
class Product {
public string $name;
public float $price;
public function __construct(string $name, float $price) {
$this->name = $name;
$this->price = $price;
}
// Clone method
public function __clone() {
}
}
$product1 = new Product("Laptop", 1200.50);
// Cloning the object
$product2 = clone $product1;
// Modifying the cloned object
$product2->price = 1500.00;
echo "Product 1 Price: " . $product1->price . PHP_EOL; // 1200.50
echo "Product 2 Price: " . $product2->price . PHP_EOL; // 1500.00
?>
Note : The __construct() method always have the public visibility factor.
Destructor
Destructor is also a special member function which is exactly the reverse of constructor
method and is called when an instance of the class is deleted from the memory.
Destructors (__destruct ( void): void) are methods which are called when there is no
reference to any object of the class or goes out of scope or about to release explicitly.
They don’t have any types or return value. It is just called before de-allocating memory
for an object or during the finish of execution of PHP scripts or as soon as the execution
control leaves the block.
Global objects are destroyed when the full script or code terminates. Cleaning up of
resources before memory release or closing of files takes place in the destructor
method, whenever they are no longer needed in the code. The automatic destruction of
class objects is handled by PHP Garbage Collector.
Note: The destructor method is called when the PHP code is executed completely by its
last line by using PHP exit() or die() functions.
<?php
class SomeClass
{
function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}
function __destruct()
{
echo "destroying " . $this->name . "\n";
}
}
$obj = new Someclass();
?>
Note: In the case of inheritance, and if both the child and parent Class have destructors
then, the destructor of the derived class is called first, and then the destructor of the
parent class.
Advantages of destructors:
Constructors Destructors
Explanation: To implement inheritance in PHP, use the extends keyword followed by the
name of the parent class. The child class inherits all public and protected properties and
methods from the parent class.
Constructor in Inheritance:
Child classes can have their own constructors, which can optionally call the parent class
constructor using parent::__construct( ).
Types of inheritance:
In PHP, inheritance is a fundamental concept of object-oriented programming (OOP)
that allows a class to inherit properties and methods from another class. There are
several types of inheritance in PHP:
1. Single Inheritance
A child class inherits from a single parent class.
class ParentClass {
public function showMessage() {
echo "This is the parent class.";
}
}
class ChildClass extends ParentClass {
}
$obj = new ChildClass();
$obj->showMessage(); // Output: This is the parent class.
2. Multilevel Inheritance
A class is derived from another derived class.
class Grandparent {
public function grandMessage() {
echo "This is the grandparent class.";
}
}
class ParentClass extends Grandparent {
public function parentMessage() {
echo "This is the parent class.";
}
}
class ChildClass extends ParentClass {
}
$obj = new ChildClass();
$obj->grandMessage(); // Output: This is the grandparent class.
3. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class ParentClass {
public function parentMessage() {
echo "This is the parent class.";
}
}
class ChildClass1 extends ParentClass {
}
class ChildClass2 extends ParentClass {
}
$obj1 = new ChildClass1();
$obj1->parentMessage(); // Output: This is the parent class.
$obj2 = new ChildClass2();
$obj2->parentMessage(); // Output: This is the parent class.
trait TraitOne {
public function methodOne() {
echo "This is method from TraitOne.";
}
}
trait TraitTwo {
public function methodTwo() {
echo "This is method from TraitTwo.";
}
}
class ChildClass {
use TraitOne, TraitTwo;
}
$obj = new ChildClass();
$obj->methodOne(); // Output: This is method from TraitOne.
$obj->methodTwo(); // Output: This is method from TraitTwo.
Abstract classes in php and interface in php are important concepts in object-oriented
programming (OOP) in PHP. An abstract class serves as a blueprint for other classes
and cannot be instantiated on its own. It can contain both concrete and abstract
methods. Abstract methods define the method signatures without providing any
implementation. Interfaces, on the other hand, define a contract that classes must
adhere to. They consist only of method signatures and constants, without any
implementation. Classes can implement multiple interfaces but can inherit from only one
abstract class. Both abstract classes and interfaces provide a way to enforce structure,
standardize behavior, and promote code reusability in PHP applications.
Abstract class in php is a class that cannot be instantiated directly but serves as a
blueprint for other classes. It provides a way to define common properties and methods
that can be inherited by its subclasses, which are regular classes that extend the
abstract class.
An abstract class is declared using the abstract keyword before the class keyword. It
can have both regular methods with implementations and abstract methods without any
implementation. Abstract methods are declared without a body and are meant to be
implemented by the subclasses. They serve as placeholders, ensuring that any class
extending the abstract class provides an implementation for those methods.
Abstract class in php are useful when you want to define a common interface or
behavior that multiple related classes should have. They provide a level of abstraction,
allowing you to define common functionality and enforce certain method
implementations in the subclasses. This promotes code reusability and helps in
organizing and structuring your codebase.
It's important to note that abstract class in php cannot be instantiated directly, meaning
you cannot create objects of the abstract class itself. However, you can create objects
of its subclasses, which inherit the properties and methods defined in the abstract class.
Example:
// Abstract Class
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
}
// Concrete Class
class Dog extends Animal {
public function makeSound() {
return "Woof!";
}
}
// Concrete Class
class Cat extends Animal {
public function makeSound() {
return "Meow!";
}
}
// Interface
interface Jumpable {
public function jump();
}
// Concrete Class implementing Interface
class Kangaroo extends Animal implements Jumpable {
public function makeSound() {
return "Boing!";
}
public function jump() {
return "Kangaroo is jumping!";
}
}
// Usage
$dog = new Dog("Buddy");
echo $dog->makeSound(); // Output: Woof!
$cat = new Cat("Whiskers");
echo $cat->makeSound(); // Output: Meow!
$kangaroo = new Kangaroo("Joey");
echo $kangaroo->makeSound(); // Output: Boing!
echo $kangaroo->jump(); // Output: Kangaroo is jumping!
In this example, we have an abstract class Animal that defines a property $name and
an abstract method makeSound(). The Dog and Cat classes extend the Animal class
and provide their own implementation of the makeSound() method. Run the above code
in your editor for a better and clear explanation.
To declare an interface in PHP, you use the interface keyword. Inside the interface, you
define the method signatures without any implementation code. These methods are
implicitly assumed to be public and must be implemented with the same visibility in the
classes that implement the interface.
A class can implement multiple interfaces by using the implements keyword followed by
a comma-separated list of interface names. When a class implements an interface, it
must provide implementations for all the methods declared in that interface. Failure to
do so will result in a fatal error.
Example:
// Interface
interface Vehicle {
public function start();
public function stop();
}
// Class implementing the interface
class Car implements Vehicle {
public function start() {
echo "Car started." . PHP_EOL;
}
public function stop() {
echo "Car stopped." . PHP_EOL;
}
}
// Class implementing the interface
class Motorcycle implements Vehicle {
public function start() {
echo "Motorcycle started." . PHP_EOL;
}
public function stop() {
echo "Motorcycle stopped." . PHP_EOL;
}
}
// Usage
$car = new Car();
$car->start(); // Output: Car started.
$car->stop(); // Output: Car stopped.
$motorcycle = new Motorcycle();
$motorcycle->start();
$motorcycle->stop();
In this example, we have an interface called Vehicle that defines two methods: start()
and stop(). The Car class and Motorcycle class both implement the Vehicle interface,
meaning they provide an implementation for both methods defined in the interface. Run
the above code in your editor for a better and clear explanation.
By implementing the interface, the Car and Motorcycle classes guarantee that they will
have the start() and stop() methods available. This allows us to create objects of these
classes and call these methods, providing a consistent interface for interacting with
different types of vehicles.
This does not contain a data member. Abstract class does contain a data
member.
The interface does not allow containers. The abstract class supports
containers.
For example, let’s say you have an abstract class named “Animal” that defines the basic
properties and methods of an animal. You also have two concrete classes named “Dog”
and “Cat” that extend the “Animal” abstract class.
In the above example, the “Animal” class is an abstract class that defines the basic
properties and methods of an animal. The “Dog” and “Cat” classes are concrete classes
that implement the “makeSound” method defined in the “Animal” class. They provide
their own implementation of the “makeSound” method, which makes them different from
each other.
Now, you can create objects of the “Dog” and “Cat” classes and call their respective
methods:
In the above example, you can create objects of the “Dog” and “Cat” classes and call
their “makeSound” method. Since the “Dog” and “Cat” classes implement the
“makeSound” method defined in the “Animal” abstract class, you can use the
“makeSound” method of the “Dog” and “Cat” objects without any issues.
Web Based Application Development with
PHP
Day 3.3:
Function Overloading:
Function overloading contains same function name and that function performs different
task according to number of arguments. For example, find the area of certain shapes
where radius are given then it should return area of circle if height and width are given
then it should give area of rectangle and others. Like other OOP languages function
overloading can not be done by native approach. In PHP function overloading is done
with the help of magic function __call(). This function takes function name and
arguments.
<?php
// PHP program to explain function
// overloading in PHP
// Creating a class of type shape
class shape {
// __call is magic function which accepts
// function name and arguments
function __call($name_of_function, $arguments) {
// It will match the function name
if($name_of_function == 'area') {
switch (count($arguments)) {
// If there is only one argument
// area of circle
case 1:
return 3.14 * $arguments[0];
// IF two arguments then area is rectangle;
case 2:
return $arguments[0]*$arguments[1];
}
}
}
}
// Declaring a shape type object
$s = new Shape;
// Function call
echo($s->area(2));
echo "\n";
// calling area method for rectangle
echo ($s->area(4, 2));
?>
Function Overriding:
Function overriding is same as other OOPs programming languages. In function
overriding, both parent and child classes should have same function name with and
number of arguments. It is used to replace parent method in child class. The purpose of
overriding is to change the behavior of parent class method. The two methods with the
same name and same parameter is called overriding.
<?php
// PHP program to implement
// function overriding
// This is parent class
class P {
// Function show of parent class
function show() {
echo "Parent";
}
}
// This is child class
class C extends P {
// Overriding show method
function show() {
echo "\nChild";
}
}
// Reference type of parent
$p = new P;
// Reference type of child
$c= new C;
// print Parent
$p->show();
// Print child
$c->show();
?>
Property and Rules of overloading in PHP:
● Property Overloading
● Method Overloading
Property Overloading:
PHP property overloading is used to create dynamic properties in the object context.
For creating these properties no separate line of code is needed. A property associated
with a class instance, and if it is not declared within the scope of the class, it is
considered as overloaded property. Following operations are performed with overloaded
properties in PHP.
● Setting and getting overloaded properties.
● Evaluating overloaded properties setting.
● Undo such properties setting.
Before performing the operations, we should define appropriate magic methods. which
are,
<?php
//
class ABC {
// Location of overloading data
private $data = array();
// Overloading not used here
public $declared = 1;
// Overloading used when accessed
// outside the class
private $hidden = 2;
// Function definition
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
// Function definition
public function __get($name) {
echo "Getting '$name: ";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
return null;
}
// Function definition
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
// Definition of __unset function
public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
// getHidden function definition
public function getHidden() {
return $this->hidden;
}
}
// Create an object
$obj = new ABC;
// Set value 1 to the object variable
$obj->a = 1;
echo $obj->a . "\n";
// Use isset function to check
// 'a' is set or not
var_dump(isset($obj->a));
// Unset 'a'
unset($obj->a);
var_dump(isset($obj->a));
echo $obj->declared . "\n\n";
echo "Private property are visible inside the class ";
echo $obj->getHidden() . "\n\n";
echo "Private property are not visible outside of class\n";
echo $obj->hidden . "\n";
?>
Method Overloading:
It is a type of overloading for creating dynamic methods that are not declared within the
class scope. PHP method overloading also triggers magic methods dedicated to the
appropriate purpose. Unlike property overloading, PHP method overloading allows
function call on both object and static context. The related magic functions are,
<?php
class ABC{
public function __call($name, $arguments) {
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
public static function __callStatic($name, $arguments) {
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
// Create new object
$obj = new ABC;
$obj->runTest('in object context');
ABC::runTest('in static context');
?>
Final keyword
Final keyword in PHP is used in different context. The final keyword is used only for
methods and classes.
Final methods:
When a method is declared as final then overriding on that method can not be
performed. Methods are declared as final due to some design reasons. Method should
not be overridden due to security or any other reasons.
<?php
// Program to understand use of
// final keyword for methods
class Base {
// Final method
final function printdata() {
echo " Base class final printdata function";
}
// Non final method
function nonfinal() {
echo "\n This is nonfinal function of base class";
}
}
// Class that extend base class
class Derived extends Base {
// Inheriting method nonfinal
function nonfinal() {
echo "\n Derived class non final function";
}
// Here printdata function can
// not be overridden
}
$obj = new Derived;
$obj->printdata();
$obj->nonfinal();
?>
Final Classes:
A class declared as final can not be extended in future. Classes are declared as final
due to some design level issue. Creator of class declare that class as final if he want
that class should not be inherited due to some security or other reasons. A final class
can contain final as well as non final methods. But there is no use of final methods in
class when class is itself declared as final because inheritance is not possible.
<?php
// Program to understand final classes
// in php
final class Base {
// Final method
final function printdata() {
echo "final base class final method";
}
// Non final method
function nonfinal() {
echo "\nnon final method of final base class";
}
}
$obj = new Base;
$obj->printdata();
$obj->nonfinal();
/* If we uncomment these lines then it will
show Class Derived may not inherit from final
class (Base)
class Derived extends Base {
} */
?>
Cloning Objects
A PHP statement such as "$obj1 = $obj2" merely creates another reference to the same
object in memory. Hence, changes in attribute reflect both in original and duplicate
object. The clone keyword in PHP creates a shallow copy of an object.
<?php
class foo {
var $var1 = 'Hello';
}
$x = new foo();
$y = $x; # reference copy
echo $x->var1 . " " . $y->var1 . PHP_EOL;
$x->var1 = "Hello World";
echo $x->var1 . " " . $y->var1 . PHP_EOL;
?>
In a shallow copy, any properties of the original object that are references to other
variables will remain references. The clone keyword does not copy the contained
objects of the copied objects.
We now create a clone of myclass object, so that $obj2 is the clone of $obj1. We
change the name property of $obj1 from Raja to Ravi, and also modify the embedded
address object. The property change will not reflect in its clone, but the referred address
object will be changed.
<?php
class address {
var $city="Nanded";
var $pin="431601";
function setaddr($arg1, $arg2) {
$this->city=$arg1;
$this->pin=$arg2;
}
}
class myclass {
var $name="Raja";
var $obj;
function setname($arg) {
$this->name=$arg;
}
}
$obj1=new myclass();
$obj1->obj=new address();
echo "original object\n";
print_r($obj1);
echo "\n";
$obj2=clone $obj1; # clone copy
$obj1->setname("Ravi");
$obj1->obj->setaddr("Mumbai", "400001");
echo "after change: Original object\n";
print_r($obj1);
echo "\nCopied object\n";
print_r($obj2);
?>
If you wish to prevent the copied object to update automatically, we need to create a
deep copy of the object with the __clone() method. It is one of the magic methods in
PHP.
Once the cloning is complete, if a __clone() method is defined, then the newly created
object's __clone() method will be called, to allow any necessary properties that need to
be changed.
<?php
class address {
var $city="Nanded";
var $pin="431601";
function setaddr($arg1, $arg2) {
$this->city=$arg1;
$this->pin=$arg2;
}
}
class myclass {
var $name="Raja";
var $obj;
function setname($arg) {
$this->name=$arg;
}
public function __clone() {
$this->obj = clone $this->obj ;
}
}
$obj1=new myclass();
$obj1->obj=new address();
echo "original object\n";
print_r($obj1);
echo "\n";
$obj2=clone $obj1; # cloned deep copy
$obj1->setname("Ravi");
$obj1->obj->setaddr("Mumbai", "400001");
echo "after change: Original object\n";
print_r($obj1);
echo "\nCloned object\n";
print_r($obj2);
?>
Deep copy and shallow copy
Shallow Copy: Shallow repetition is quicker. However, it’s “lazy” it handles pointers and
references. Rather than creating a contemporary copy of the particular knowledge the
pointer points to, it simply copies over the pointer price. So, each of the first and
therefore the copy can have pointers that reference constant underlying knowledge.
Deep Copy: Deep repetition truly clones the underlying data. It is not shared between
the first and therefore the copy.
Shallow Copy stores the copy of Deep copy stores the copy of the
the original object and points the original object and recursively
references to the objects. copies the objects as well.
A shallow copy is faster. Deep copy is comparatively slower.
Most often we need to store a complex array in the database or in a file from PHP.
Some of us might have surely searched for some built-in function to accomplish this
task. Complex arrays are arrays with elements of more than one data-types or array.
But, we already have a handy solution to handle this situation. We don’t have to write
our own function to convert the complex array to a formatted string. There are two
popular methods of serializing variables.
● serialize()
● unserialize()
We can serialize any data in PHP using the serialize() function. The serialize() function
accepts a single parameter which is the data we want to serialize and returns a
serialized string. Below program illustrate this:
<?php
// a complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// convert to a string
$string = serialize($myvar);
// printing the serialized data
echo $string;
?>
From the above code, we have a variable with serialized data, $string . We can
unserialize the value of the variable using unserialize() function to get back to the
original value of the complex array, $myvar.
<?php
// a 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);
?>