GuidePedia

0
PHP OOP Concepts

Object Oriented Programming  is a paradigm which is nowadays the most popular way to develop any application and most of the modern day language is based on this paradigm.
OOP or Object Oriented Programming PHP has so many features like:
Class
Object
Polymorphism
Dynamic Binding...etc.
In this series of tutorial you will come to know about all the features of these features using PHP syntax.
PHP Class Object
In object oriented programming a class can be an abstract data type, blue print or template. You could consider the name of a class as noun like name of a person, place or thing. For example Fruit is a class, where apple, orange are the object of this class.
PHP Constructor and Destructor
In this current tutorial we will study about constructor and destructor of OOP.Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor
method is called for every object creation.
PHP Class Constant
In this tutorial we will study how to declare a class constant in PHP. Sometimes we need to have constant values in our program which remains same through and through. We do not need to put a '$' sign before the constant to use or to declare it. 
PHP Create Instance
In the current tutorial we will study how to instantiate an object in PHP. Example will help you to learn it precisely. You will also come to know about the use of new, -> operator.
PHP Inheritance Class
Inheritance is a property of Object Oriented Programming, PHP also supports this principle in its programming as object model. With the help of this property classes and objects get more flexibility, scalability in programming
PHP Mutator Accessor
In object-oriented programming, the mutator method (also called "setter") is used to initialize the member variables of a class. On the other hand accessor methods are used to get the values of the private data member.
PHP Autoload 
It is very common in PHP programming that we need to write long listing of files which has to be include in a single file. It is indeed a hectic job for each PHP programmer.
PHP Static Variable and Methods
In this tutorial we will study when we should use static methods and variables. Static keyword is used to make only one copy of the variable for the class. If we declare a method as static then we can access the method using class, without instantiating any object. 
PHP Abstract Class
In this tutorial we will study about abstract class in PHP, how to declare, use an abstract class etc. Examples will help you to understand the concepts of abstract class more precisely.

PHP Access Specifiers
In the current tutorial we will get to know about different types of access specifiers or visibility in PHP. You will also come to know that what could be difference in public, private and protected access specifiers. What could be the difference if we use these keywords before a method and before variables. Examples will exemplify each of the above concepts
PHP Interface Class
In this tutorial you will study about interface of PHP, how to declare and implement an interface, what points should be kept in mind when we declare an interface etc. Interface is also a class but it has few constraints unlike any other ordinary concrete class and it supports the multiple inheritance.
PHP Polymorphism Function
PHP Polymorphism Function is one of the feature of OOP. Generally we get polymorphism in two ways: Compile time, Run time. In this tutorial we will study about which polymorphism is supported by PHP and which one is not.
PHP Object Iteration
This PHP tutorial will introduce a new feature which has been introduced in PHP 5 called Object iteration. In PHP 5 a new way for objects is introduced to iterate through a list of items. In this technique we generally use foreach statement. 
PHP Design Patterns
In this tutorial we will study what is a design pattern and in the subsequent pages we will study about various design patterns supported by PHP. A design pattern is like a template which guides us to solve a problem. Design patterns are not finished design that can be transformed directly into code. In Object Oriented based design patterns we can get the interactions and relationships between classes or objects.
PHP Factory Method
It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling. In this case factory pattern helps us a lot. In the current tutorial we will study about factory method and how to implement this in PHP.
PHP Singleton Method
In the current php tutorial we will study about singleton pattern of PHP, which is another type of designing pattern. Examples will help you understand in better way. 
PHP Observer Method
In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need..
PHP OOP Namespace
The term namespace is very much common in OOP based language, basically it is a collection of classes, objects and functions. Namespace is one of the major change in PHP 5.3.0. Naming collision of classes, functions and variables can be avoided. 
PHP Object Reference
In this current tutorial we will study about what is object and what is reference? how to create object in PHP, how to give reference to another object etc. In PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.
PHP Comparison Objects
In this current tutorial we will study about the various ways of comparing two objects. There are several ways are provided in PHP to compare two objects of class (same or different)like ==,=== etc operators are present to compare two objects. 
PHP Type Hinting
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type

PHP Final Keyword
In this current tutorial we will study about final keyword, final keyword helps us to put some constraint on classes and it's methods. Using final keyword a class can not be inherited and a method can not be overridden.
PHP Object Reference
In this current tutorial we will study about what is object and what is reference? how to create object in PHP, how to give reference to another object etc. In PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.
PHP Comparison Objects
In this current tutorial we will study about the various ways of comparing two objects. There are several ways are provided in PHP to compare two objects of class (same or different)like ==,=== etc operators are present to compare two objects. 
PHP Type Hinting
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type
PHP Late Static Binding
In this current PHP tutorial Section, we will study about late static binding in PHP, what is late static binding, how to use late static binding among classes, what are the uses of it in PHP etc.
PHP Magic Methods
In this PHP tutorial you will come to know about various methods which are called as magic methods. This is the first page on this topic and the subsequent pages will help you to understand each and every magic method precisely. 
PHP Sleep Wakeup Method
This is one of the magic method provided by PHP. The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely and __wakeup() of PHP is used to reestablish the database connections that may have been lost during any phenomenon.
PHP toString Function
In PHP 5.3.0 a method has been introduced called toString(), basic functionality of the method is to print an object, how? current tutorial is trying to focus on this topic.
PHP invoke Method
Have you ever wondered that how to call an object as function? Thanks to __invoke method, introduced in PHP 5.3.0, with the help of this function we can do it. The present tutorial is all about this PHP invoke function.
PHP set static Method
In this current tutorial we will study about a new method called __set_static(), which is introduced in PHP 5. With the help of this method we can assign values to a new object dynamically. Examples will help to understand the concept
PHP Clone Object
In this PHP tutorial, we will study about cloning of object, how to make a clone object, what are the process of cloning in PHP 5 and how is it different from PHP 4
PHP References Explained
This tutorial covers three basic operations performed by references, assigning values by references, passing by references, returning by references etc. In PHP references means to access the same variable by two or more different names.


PHP OOP Concepts:-
Object Oriented Programming  is a paradigm which is nowadays the most popular way to develop any application and most of the modern day language is based on this paradigm.
OOP or Object Oriented Programming PHP has so many features like:
  1. Class
  2. Object
  3. Polymorphism
  4. Dynamic Binding...etc.
In this series of tutorial you will come to know about all the features of these features using PHP syntax.
In object oriented programming a class can be an abstract data type, blue print or template. You could consider the name of a class as noun like name of a person, place or thing. For example Fruit is a class, where apple, orange are the object of this class.
PHP Class Object:
In object oriented programming a class can be an abstract data type, blue print or template. You could consider the name of a class as noun like name of a person, place or thing.  For example Fruit is a class, where apple, orange are the object of this class.
Object is the instantiate of a class. A class consists of a member variable and methods. In PHP we need to declare the access specifiers (public, private, or protected) separately for
PHP Object Class Example:
<?php
class A
{
public function disp(){
echo "Inside the class<br/>";
}}
$a=new A();
$a->disp();
A::disp();
?>
Output:
Inside the class
Inside the class
Explanation:
In the above programming we create a class named A, it has a publically declared function disp(), on the outer side of the class we instantiate the object $a, we  call the function disp with -> operator. Any class can access it's member using :: operator.
PHP Constructor and Destructor:-

In this current tutorial we will study about constructor and destructor of OOP.Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor method is called for every object creation.
Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor method is called for every object creation.
We can call parent's constructor method using parent::__construct() from the child constructor.
PHP also supports destructor like C++. This method is called as soon as the references of the object are removed or if we destroy the object . This feature has been included in PHP 5. Like constructor method we can call the destructor method of parent class by parent::__destruct().
The destructor is being called any how, means even after executing the exit() code destructor method could be called.
PHP Constructor & Destructor Example:
<?php
class ParentClass{
function __construct(){
print "In parent class <br/>";}}
class ChildClass extends ParentClass{
function __construct(){
parent::__construct();
print "In child class";}}
$obj1=new ParentClass(12);
$obj2=new ChildClass();   ?>
Output:-
In parent class
In parent class
IIn child class
Example:
<?php
class ParentClass{
function __construct(){
print "In parent class <br/>";
}
function __destruct(){
print "Parent Class Destructor called<br/>";
}
}
class ChildClass extends ParentClass{
function __construct(){
parent::__construct();
print "In child class<br/>";
}
function __destruct(){
print "Child Class Destructor called<br/>";
}
}
$obj1=new ParentClass();
$obj2=new ChildClass();
?>
Output:
In parent class
In parent class
In child class
Child Class Destructor called
Parent Class Destructor called
PHP Class Constant:-
In this tutorial we will study how to declare a class constant in PHP. Sometimes we need to have constant values in our program which remains same through and through. We do not need to put a '$' sign before the constant to use or to declare it.
Sometimes we need to have constant values  in our program which remains same through and through. We do not need to put a $ sign before the constant to use or to declare it.
The value of the constant should remain unchanged that means it must be a constant expression.
Example:
<?php
class A
{
const newValue="Constant value does not consist $ sign";
function display()
{
echo self::newValue."\n";
}
}
$a=new A();
$a->display();
?>
Output:
Constant value does not consist $ sign
Explanation:
In the above example there is a single class declaration named A. Outside of this class
PHP Create Instance:-
In the current tutorial we will study how to instantiate an object in PHP. Example will help you to learn it precisely. You will also come to know about the use of new, -> operator.
Create an Instance:
In OOPs programming we need to instantiate each object. In the following example we create two classes A and B. To access variables of the class we should use self keyword following with double colon sign.
When we need to access the variables of a class from an object we use -> operator sign. To instantiate an object we need to use new operator as:
object-name=new class-name();
Following example is based on these concept, go through the example and run it on your computer, you will come to know how it works:
How to Create PHP Instance with Example:
<?php
class A
{
public static $one;
public function set($one){
self::$one=$one;
}
public function get(){
echo "Value of variable is:".self::$one;}
}
class B
{
public function disp(){
echo "<br/>Inside Class B";}
}
$a=new A();
$a->set(12);
$a->get();
$class='B';
$a=new $class();
$a->disp();
?>
Output:
Value of variable is:12
Inside Class B
PHP Inheritance Class:-
Inheritance is a property of Object Oriented Programming, PHP also supports this principle in its programming as object model. With the help of this property classes and objects get more flexibility, scalability in programming.
nheritance is a property of Object Oriented Programming, PHP also supports this principle in its programming as object model. With the help of this property classes and objects  get more flexibility, scalability in programming
At the same time we must keep in our mind that when we should not use the inheritance. We must not use inheritance when we have only different values in classes, we must use the inheritance when the structure and the behavior are different. It is always advisable that we must give preference to object composition over inheritance.
 In the following example we will come to know how a class could be declared as a child class of another class using extends keyword.
PHP Inheritance Example:
<?php
class One
{
public function printItem($string)
{
echo 'This argument is passing from '.$string.'<br/>';
}
}
class Two extends One
{
}
$baseObj=new One();
$childObj=new Two();
$baseObj->printItem("Base");
$childObj->printItem("Child");
?>
Output:
This argument is passing from Base
This argument is passing from Child
PHP Mutator Accessor:-
In object-oriented programming, the mutator method (also called "setter") is used to initialize the member variables of a class. On the other hand accessor methods are used to get the values of the private data member.
PHP Mutator and Accessor Methods:
In object-oriented programming, the mutator method (also called "setter") is used to initialize the member variables of a class. According to the encapsulation principle the variables of the class are declared as private to protect and can be modified by a public declared function.
On the other hand accessor methods are used to get the values of the private data member.
These methods can be implemented on non-object-oriented programming language as well. In this case we have to pass the address (reference) of the variable.
PHP Mutator Method Example:
<?php
class One{
private $string;
public function mutator($arg){
$this->string=$arg;}
public function accessor(){
echo "Value is: ".$this->string;}}
$one=new One();
$one->mutator("roseindia");
$one->accessor();
?>
Output:
Value is: roseindia
PHP Autoload:-
It is very common in PHP programming that we need to write long listing of files which has to be include in a single file. It is indeed a hectic job for each PHP programmer.
PHP Autoloading Classes:
It is very common in PHP programming that we need to write long listing of files which has to be include in a single file. It is indeed a hectic job for each PHP programmer.
But with the advent of PHP 5.0, this is not necessary anymore. We can define an   _autoload function to call automatically the class/interface which has not been defined yet.
PHP Autoload
Posted on: February 19, 2010 at 12:00 AM
It is very common in PHP programming that we need to write long listing of files which has to be include in a single file. It is indeed a hectic job for each PHP programmer.
PHP Autoloading Classes:
It is very common in PHP programming that we need to write long listing of files which has to be include in a single file. It is indeed a hectic job for each PHP programmer.
But with the advent of PHP 5.0, this is not necessary anymore. We can define an   _autoload function to call automatically the class/interface which has not been defined yet.
PHP Autoload Class Example:
<?php
function _autoload($classname){
require_once $classname.'.php';
}
$obj=new mysqli();
?>
No Output will be generated
PHP Static Variable and Methods:-
In this tutorial we will study when we should use static methods and variables. Static keyword is used to make only one copy of the variable for the class. If we declare a method as static then we can access the method using class, without instantiating any object.
PHP Static Methods and Variables:
In this tutorial we will study when we should use static methods and variables.
Static keyword is used to make only one copy of the variable for the class. All objects of that class will access one copy of that attribute. Static data are used when some data has to share within the all objects of that class.
If we declare a method as static then we can access the method using class, without instantiating any object.
Example of PHP Static Variables & Methods :
<?php
class One{
private static $var=0;
function __construct(){
echo "Inside constructor";
self::$var++;
print self::$var;}
static function disp(){
print self::$var;}}
One::disp();
?>
Output:
0
PHP Abstract Class:-
In this tutorial we will study about abstract class in PHP, how to declare, use an abstract class etc. Examples will help you to understand the concepts of abstract class more precisely.
PHP Abstract Class:
Abstract classes and methods are introduced in PHP 5. The concept behind the abstract class is that we need to extend this class by its descendant class(es). If a class contains abstract method then the class must be declared as abstract. Any method which is declared as abstract must not have the implementation part but the declaration part only.
The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
PHP Abstract Class Example:
<?php
abstract class One{
public function disp(){
echo "Inside the parent class<br/>";
}
}
class Two extends One{
public function disp(){
echo "Inside the child class<br/>";
}
}
class Three extends One{
//no method is declared
}
$two=new Two();
echo "<b>Calling from the child class Two:</b><br/>";
$two->disp();
echo "<b>Calling from the child class Three:</b><br/>";
$three=new Three();
$three->disp(); 
?>
Output:
Calling from the child class Two:
Inside the child class
Calling from the child class Three:
Inside the parent class
Example:
<?php
abstract class One{
abstract function disp();
}
class Two extends One{
public function disp(){
echo "Inside the child class<br/>";
}
}
class Three extends One{
public function disp(){
echo "Inside the child class 2<br/>";}
}
$two=new Two();
echo "<b>Calling from the child class Two:</b><br/>";
$two->disp();
echo "<b>Calling from the child class Three:</b><br/>";
$three=new Three();
$three->disp();
?>
Output:
Calling from the child class Two:
Inside the child class
Calling from the child class Three:
Inside the child class 2
PHP Access Specifiers:-
In the current tutorial we will get to know about different types of access specifiers or visibility in PHP. You will also come to know that what could be difference in public, private and protected access specifiers. What could be the difference if we use these keywords before a method and before variables. Examples will exemplify each of the above concepts.
PHP Interface Class:-
In this tutorial you will study about interface of PHP, how to declare and implement an interface, what points should be kept in mind when we declare an interface etc. Interface is also a class but it has few constraints unlike any other ordinary concrete class and it supports the multiple inheritance.
PHP Interface Class:
PHP does not support multiple inheritance directly, to implement this we need Interface. It is much similar to Interface of Java.
In PHP, signature of the method are declared in the Interface body, and the body part of the method is implemented in derived class. Variables are declared as constant and it can not be changed in the child classes.
We use implement keyword to extend this kind of class, at the same time we can implement more than one interface and one interface can be implemented by another interface.
All methods declared in an interface must be public and the variables should be constant.
This is mandatory that we must declare the body part of the method in the derived class otherwise an error message will be generated.
Example:
<?php
interface Inter{
const a="This is constant value";
public function disp(); }
class A implements Inter{
function show(){
echo self::a."<br/>";}
public function disp(){
echo "Inside the disp function";}}
$a=new A();
$a->show();
$a->disp();
?>
Output:
This is constant value
Inside the disp function
PHP Polymorphism Function:-
PHP Polymorphism Function is one of the feature of OOP. Generally we get polymorphism in two ways: Compile time, Run time. In this tutorial we will study about which polymorphism is supported by PHP and which one is not.
PHP Polymorphism Function:
The PHP Polymorphism Method is one of the feature of OOP language. Generally we get polymorphism in two ways:
Ø      Compile time
Ø      Run time
Compile time polymorphism PHP is like function overloading, operator overloading etc. In Polymorphism function overloading we can create more than one function with same name but with different signature that means it could have different number of parameters, different datatype of the parameter etc. Depending on the actual number and/or the data type the compiler resolve the actual call .
In operator overloading predefined operators treat as functions and one object calls this function and passes another object as argument. PHP neither supports operator overloading nor function overloading.
Inheritance and virtual functions are the examples of PHP Run time polymorphism. PHP supports Inheritance as well as virtual function as function overriding.
Following examples will exemplify each of the types of polymorphism:
PHP Polymorphism Function Example:
<?php
class A{
function Disp(){
echo "Inside the Base class<br/>";}}
class B extends A{
function Disp(){
echo "Inside the Chlid class<br/>";}}
class C extends A{
}
$obj=new B();
$obj->Disp();
$obj2=new C();
$obj2->Disp();
?>
Output:
Inside the Chlid class
Inside the Base class
PHP Object Iteration:
This PHP tutorial will introduce a new feature which has been introduced in PHP 5 called Object iteration. In PHP 5 a new way for objects is introduced to iterate through a list of items. In this technique we generally use foreach statement.
PHP Object Iteration:
In PHP 5 a new way for objects is introduced to iterate through a list of items. In this technique we generally use foreach statement. All visible (public, protected) properties are used in the iteration. To display the private properties we can use any method which would display these all.
PHP Object Iteration Example:
<?php
class One{
public $a="A";
public $b="B";
public $c="C";
protected $pro="Protected Data";
private $pri="Private Data";
function iteration(){
echo "One::iteration<br/>";
foreach($this as $key=>$value){
print "$key=>$value<br/>";}}
}
$one=new One();
echo "<b>If we call the iteration method:</b><br/>";
$one->iteration();
echo "<b>If we iterate the object:</b><br/>";
foreach($one as $key=>$value){
print "$key=>$value<br/>";
}
?>
Output:
If we call the iteration method:
One::iteration
a=>A
b=>B
c=>C
pro=>Protected Data
pri=>Private Data
If we iterate the object:
a=>A
b=>B
c=>C
PHP Design Patterns:-
In this tutorial we will study what is a design pattern and in the subsequent pages we will study about various design patterns supported by PHP. A design pattern is like a template which guides us to solve a problem. Design patterns are not finished design that can be transformed directly into code. In Object Oriented based design patterns we can get the interactions and relationships between classes or objects.
PHP Design Patterns:
A design pattern is like a template which guides us to solve a problem. Design patterns are not finished design that can be transformed directly into code. In Object Oriented based design patterns we can get the interactions and relationships between classes or objects.
It is not necessary that every software patterns are design patterns. Design patterns generally persists in the domain of modules.
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides were introduced design patterns and this was foreword by Grady Booch.
There are almost 23 patterns present and these are based on different categories like Creation patterns, Structural patterns, and Behavioral patterns.
Now we will study five common design patterns in PHP 5:
PHP Factory Method:-
It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling. In this case factory pattern helps us a lot. In the current tutorial we will study about factory method and how to implement this in PHP.
PHP Singleton Method:-
In the current php tutorial we will study about singleton pattern of PHP, which is another type of designing pattern. Examples will help you understand in better way.
PHP Observer Method:-
In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need..
PHP Factory Method:-
It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling. In this case factory pattern helps us a lot. In the current tutorial we will study about factory method and how to implement this in PHP.
PHP Factory Method:
It is very common problem that sometimes we need to change a little in our coding and subsequently we have to change so many places like in other class, function etc. It is called tight coupling.
In bigger projects/programs a big section of coding is heavily depend on a class or a function. Like if we would like to change the data provider, suppose from XML file to database or vice versa or any other kind of file then we have to change lots of coding.
In this case factory pattern helps us a lot. The factory method is a class which is used to create objects. Using this class we can create object without using new operator. In this way if we want change the type of the object, all we need to do is change the factory.
It is advisable that we should always use factory methods instead of constructors because it has following benefits over it:
  1. Every factory method name should be different
  2. We can create objects of same class type as well as of derived class type.
  3. Unlike constructors factory methods need not to create or initialize the methods all the time.
  4. Factory methods can be virtual but constructors can not be virtual.
  5. Factory methods can select to create objects of different types.
PHP Factory Method Example:
<?php
interface student{
function getName();}
class stuPersonal implements student{
public function getName(){
return "rose";}
public function __construct($roll){}
}
class studentFactory{
public static function create($roll){
return new stuPersonal($roll);}
}
$stu=studentFactory::create(1);
echo $stu->getName();
?>
Output:
rose
PHP Singleton Method:-
In the current php tutorial we will study about singleton pattern of PHP, which is another type of designing pattern. Examples will help you understand in better way.
PHP Singleton Method:
Many application resources are exclusive like database, in that case the class should have a single object. The connection to a database is exclusive.
The singleton pattern is exactly the same, it uses for creating single object.
To get an instance of the singleton pattern we must have an accessor method in our program that will return an instance of the class but it will not allow to instantiate more than one instance at a time. In programming example we will create an object manually,
PHP Singleton Pattern Example:
<?php
final class single
{
protected static $_var;
private function __construct()
{ }
private function __clone()
{ }
public static function createObject()
{
if( self::$_var === NULL ) {
self::$_var = new self();
}
return self::$_var;
}
}}
$obj = Singleton::reateObject();
?>
PHP Observer Method:-
In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need..
The PHP Observer Pattern:
In the previous tutorial on Factory method we have studied about tight coupling and the drawbacks of the tight coupling and how to avoid it using Factory method, Observer method works the same. This method is also known as Dependents, Publish-Subscribe, Model-View.
In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need.
This pattern is useful for dynamic relationships between objects, we can add a new object when the program is running.
For example many applications (like spreadsheet) have data model and whenever we change the data model, it reflects in the overall application.
Benefit of this pattern is that it reduces the degree of coupling. The subject does not need to know much about the observer rather it allows the observer to subscribe and whenever and whatever changes occur subject passes the message to each of it's observer object. 
PHP Observer Method Example:
<?php
interface Observer
{
function onChanged($sender, $args);
}
interface Observable
{
function addObserver($observer);
} 
class StudentList implements Observable
{
private $_observers = array();
public function addStudent( $name )
{
foreach( $this->_observers as $obs )
$obs->onChanged( $this, $name );
}
public function addObserver( $observer )
{
$this->_observers []= $observer;
}
} 
class StudentListLogger implements Observer
{
public function onChanged($sender, $args){
echo ("$args added to Student list\n");
}
} 
$sl = new StudentList();
$sl->addObserver( new StudentListLogger() );
$sl->addStudent( "Rose" );
?>
Output:
Rose added to Student list
PHP OOP Namespace:-
The term namespace is very much common in OOP based language, basically it is a collection of classes, objects and functions. Namespace is one of the major change in PHP 5.3.0. Naming collision of classes, functions and variables can be avoided.
Namespace in PHP:
The term namespace is very much common in OOP based language, basically it is a collection of classes, objects and functions.
Namespaces are one of the major change in PHP 5.3.0. Naming collision of classes, functions and variables can be avoided.
We can put any code of PHP within a namespace, but in general class, functions, and constants are placed for easy identification and retrieval.
A namespace is declared with namespace keyword, but we should keep remember that namespace is introduced in PHP 5.3.0 and if we try this in older version of PHP then a error message would appear. The namespace should always declare on the top of the page.
PHP OOP Namespace Example:
<?php
namespace MyProject;
?>
Exaplanation:
We should declare the namespace as above and we can also place a backslash between multiple names of namespace.
PHP Object Reference:-
In this current tutorial we will study about what is object and what is reference? how to create object in PHP, how to give reference to another object etc. In PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.
PHP Object and References:
It is a very common misconception about object that the terms object and reference is interchangeable. Now we must know what is actually an object and what is a reference.
Whenever an object is instantiated it occupies some memory, that memory chunk is called an object and the name or identifier which refers to that memory chunk is called a reference. But in general we call the first reference of that memory chunk as object and the objects which are used to refer the first object as reference.
Similarly in PHP a reference is an alias and an object variable does not contain the object rather it contains the identifier and it allows to access the actual object.  
Example:
<?php
class A{
public $var=2;
}
$a=new A();
$b=$a;
$b->var=4;
echo "\$a=".$a->var."<br/>";
$c=new A();
$d=&$c;
$d->var=43;
echo "\$c=".$c->var."<br/>";
function display($obj){
$obj->var=34;
}
$e=new A();
display($e);
echo "\$c=".$e->var."<br/>";
?>
Output:
$a=4
$c=43
$c=34
PHP Comparison Objects:-
In this current tutorial we will study about the various ways of comparing two objects. There are several ways are provided in PHP to compare two objects of class (same or different)like ==,=== etc operators are present to compare two objects.
Comparison of Objects:
There are several ways are provided in PHP to compare two objects of class (same or different).
There are mainly = =, = = = operators are used to compare two objects, and instance of operator can be used also.
The operator = =  checks the attributes and values of objects and returns true if the objects are of same class and has equal values.
The operator = = = checks two objects and returns true if both refers two the same object a class.
Instance of is an operator which is used to check whether an object is an instance of a class or not. Following examples will exemplify these operators:
Example:
<?php
class A{
public $one;
 }
class B{
public $two;
public function display(){
}
}
$obj1=new A();
$obj2=new B();
$obj3=new A();
$obj4=$obj1;
echo "<b>Comparison of two objects of same class</b>";
compareObjects($obj1,$obj3);
echo "<br/><b>Comparison of two objects of different class</b>";
compareObjects($obj1,$obj2);
echo "<br/><b>Comparison of two references of same object</b>";
compareObjects($obj1,$obj4);
function compareObjects($obj1,$obj2){
echo "<br/>Using = = operator";
echo "<br/>Objects are same: ".op1($obj1,$obj2);
echo "<br/>Using instanceof operator";
echo "<br/> Objects are same: ".instance($obj1,$obj2);
echo "<br/>Using = = = operator";
echo "<br/> Objects are same: ".op2($obj1,$obj2);
}
function op1($obj1,$obj2){
if($obj1==$obj2)return "true";
else return "false";
}
function instance($obj1,$obj2){
if(($obj1 instanceof A)&&($obj2 instanceof A)) return "true";
else return 'false';
}
function op2($obj1,$obj2){
if($obj1===$obj2)return "true";
else return "false";
}
?>
Output:
Comparison of two objects of same class
Using = = operator
Objects are same: true
Using instanceof operator
Objects are same: true
Using = = = operator
Objects are same: false
Comparison of two objects of different class
Using = = operator
Objects are same: false
Using instanceof operator
Objects are same: false
Using = = = operator
Objects are same: false
Comparison of two references of same object
Using = = operator
Objects are same: true
Using instanceof operator
Objects are same: true
Using = = = operator
Objects are same: true
PHP Type Hinting:-
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type
PHP Type Hinting Function:
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array. Type Hints only supports object and array type, other primitive types like int and string are not supported.
Go through each example and read the error message carefully then you will come to know about the cause of the error and type hinting more preciously.
If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type.
Example :
<?php
class One{
function arraytest(array $arr){
print_r ($arr);
}
}
$one=new One;
$one->arraytest("a string");
?>
Output:
Catchable fatal error: Argument 1 passed to One::arraytest() must be an array, string given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 10 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.
Example :
<?php
class One{
function arraytest(array $arr){
print_r ($arr);
}
}
$one=new One;
$one->arraytest(array('a','s'));
?>
Output:
Array ( [0] => a [1] => s ) Array ( [0] => a [1] => s ) 
Example:
<?php
class One{
function other_class_test(Two $two){
echo $two->var;
}
}
class Two{
public $var="This is a variable ";
}
$one=new One;
$obj=new Two;
$one->other_class_test($obj);
?>
Output:
This is a variable .
Example:
<?php
class One{
function other_class_test(Two $two){
echo $two->var;
}
}
class Two{
public $var="This is a variable ";
}
class NewClass
{
public $var="Another variable";
}
$one=new One;
$obj=new NewClass;
$one->other_class_test($obj);
?>
Output:
Catchable fatal error: Argument 1 passed to One::other_class_test() must be an instance of Two, instance of NewClass given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 17 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.
PHP Final Keyword:-
In this current tutorial we will study about final keyword, final keyword helps us to put some constraint on classes and it's methods. Using final keyword a class can not be inherited and a method can not be overridden.
Final Keyword in PHP:
If you are familiar with Java then you must know the functionality of Final keyword. Final keyword prevents child classes from overriding a method of super or parent class. If we declare a class as final then it could not have any child class that means no class can inherit the property of this class.
PHP Final Keyword Example:
<?php
class A
{
final public function disp(){
echo "Inside the final function";
}
}
class B extends A
{
function disp(){
echo "Inside the final function";
}
}
$obj=new B();
$obj->disp();
?>
Output:
Fatal error: Cannot override final method A::disp() in C:\xampp\htdocs\PHP-AJAX\final.php on line 14
Example:
<?php
final class A
{
public function disp(){
echo "Inside the final function";
}
}
class B extends A
{
function disp(){
echo "Inside the final function";
}
}
$obj=new B();
$obj->disp();
?>
Output:
Fatal error: Class B may not inherit from final class (A) in C:\xampp\htdocs\PHP-AJAX\final.php on line 14
PHP Type Hinting:-
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type
PHP Type Hinting Function:
Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array. Type Hints only supports object and array type, other primitive types like int and string are not supported.
Go through each example and read the error message carefully then you will come to know about the cause of the error and type hinting more preciously.
If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type.
Example :
<?php
class One{
function arraytest(array $arr){
print_r ($arr);
}
}
$one=new One;
$one->arraytest("a string");
?>
Output:
Catchable fatal error: Argument 1 passed to One::arraytest() must be an array, string given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 10 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.
Example :
<?php
class One{
function arraytest(array $arr){
print_r ($arr);
}
}
$one=new One;
$one->arraytest(array('a','s'));
?>
Output:
Array ( [0] => a [1] => s ) Array ( [0] => a [1] => s ) 
Example:
<?php
class One{
function other_class_test(Two $two){
echo $two->var;
}
}
class Two{
public $var="This is a variable ";
}
$one=new One;
$obj=new Two;
$one->other_class_test($obj);
?>
Output:
This is a variable .
Example:
<?php
class One{
function other_class_test(Two $two){
echo $two->var;
}
}
class Two{
public $var="This is a variable ";
}
class NewClass
{
public $var="Another variable";
}
$one=new One;
$obj=new NewClass;
$one->other_class_test($obj);
?>
Output:
Catchable fatal error: Argument 1 passed to One::other_class_test() must be an instance of Two, instance of NewClass given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 17 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.
PHP Late Static Binding:-
In this current PHP tutorial Section, we will study about late static binding in PHP, what is late static binding, how to use late static binding among classes, what are the uses of it in PHP etc.
PHP Late Static Binding:
A new feature called late static binding is introduced in PHP 5.3.0 which can be used to refer the called class.
The name late static binding is coined because of the static:: will no longer be resolved using the class where the method is defined.
Example:
<?php
class One {
public static function classIdentifier() {
echo __CLASS__;
}
public static function classtest() {
self::classIdentifier();
}
}
class Two extends One {
public static function classIdentifier() {
echo __CLASS__;
}
}
Two::classtest();
?>
Output:
One
Example:
<?php
class One {
public static function classIdentifier() {
echo __CLASS__;
}
public static function classtest() {
static::classIdentifier();
}
}
class Two extends One {
public static function classIdentifier() {
echo __CLASS__;
}
}
Two::classtest();
?>
Output:
Two
PHP Magic Methods:-
In this PHP tutorial you will come to know about various methods which are called as magic methods. This is the first page on this topic and the subsequent pages will help you to understand each and every magic method precisely.
Magic Methods in PHP:
In PHP there are so many methods are included in recent versions, magic methods are one of them. The magic methods are listed below:
  1. __construct()
  1. __destruct()
  1. __call()
  1. __callStatic()
  1. __get()
  1. __set()
  1. __isset()
  1. __unset()
  1. __sleep()
  1. __wakeup()
  1. __toString()
  1. __invoke()
  1. __set_state()
  1. __clone()
In the above list of the magic methods it is very easy to identify that every magical method name is started with " __ " sign. We can not declare any user-defined functions with __ sign, and we can not use the magic methods name in any user-defined functions.
The following links will describe magic methods:
PHP Constructor and Destructor:-
In this current tutorial we will study about constructor and destructor of OOP.Like other OOP based languages PHP also supports constructor method for classes. As any other language's constructor method, in PHP constructor method is called for every object creation.
PHP Sleep Wakeup Method:-
This is one of the magic method provided by PHP. The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely and __wakeup() of PHP is used to reestablish the database connections that may have been lost during any phenomenon.
PHP toString Function:-
In PHP 5.3.0 a method has been introduced called toString(), basic functionality of the method is to print an object, how? current tutorial is trying to focus on this topic.
PHP Sleep Wakeup Method:-
This is one of the magic method provided by PHP. The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely and __wakeup() of PHP is used to reestablish the database connections that may have been lost during any phenomenon.
The __sleep and __wakeup Function in PHP
The __sleep function in PHP is useful when we have very large objects in our program and we do not want to save the object completely, this method is useful for commit pending or for purging purpose.
The serialize method checks every program whether it has a magic method __sleep or not. If so, then the function execute that method prior to any other function moreover it can clean up the object and will return an array which contains the name of each variable.
On the other hand __wakeup is used to reestablish the database connections that may have been lost during any phenomenon like serialization or reinitialization tasks. unserialize() method checks the presence of __wakeup() function in a program, if so then it reconstruct any resources that the object may have.
PHP Sleep and Wakeup Method Example:
<?php
class DBConnection{
private $host, $user, $password,$link,$db;
public function __construct($host, $user, $password,$db)
{
$this->host=$host;
$this->user=$user;
$this->password=$password;
$this->db=$db;
$this->connect();
}
private function connect()
{
$this->link=mysql_connect($this->host,$this->user,$this->password);
mysql_select_db($this->db,$this->link);
if(! $this->link)die("Could not connect").mysql_error();
else echo"Connected<br/>";
}
function __sleep()
{
return array($host,$user,$password,$db);
}
function __wakeup()
{
$this->connect();
}
}
$var=new DBConnection("localhost","root","","ajax");
$var->__wakeup();
?>
Output:
Connected
Connected
PHP toString Function:-
In PHP 5.3.0 a method has been introduced called toString(), basic functionality of the method is to print an object, how? current tutorial is trying to focus on this topic.
__toString method in PHP:
In the previous versions of PHP it is not possible to convert an object to a string value, but with the invent of _toString method now it is just a function call away.
This method is called implictly, whenever an object is instantiated we need to pass a string value to the __construct() function (the constructor ) and assign the value to a variable. After instantiation of the object, if we try to print the object, __toString() function is called implicitly and print the value of the member variable.
PHP toString Function Example:
<?php
class A
{
private $var;
public function __construct($var){
$this->var=$var;
}
public function __toString()
{
return $this->var;
}
}
$obj=new A('Hi');
echo $obj;
?>
Output:
Hi
PHP invoke Method:-
Have you ever wondered that how to call an object as function? Thanks to __invoke method, introduced in PHP 5.3.0, with the help of this function we can do it. The present tutorial is all about this PHP invoke function.
__invoke() Function in PHP:
PHP 5.3.0 has introduced so many new concepts, new functions. __invoke() is one of them. The functionality of __invoke() method is quite different from others. It is new and elegant in this class. Have you ever heard that we can call an object as function? I suppose no, but with the help of __invoke() method it is possible and just because of it's magical property it is included in magic methods.
So, let's try to evaluate what is it actually and how it works? Hope the following example will exemplify:
PHP Invoke Method Example:
<?php
class A
{
public function __invoke($var){
var_dump($var);
echo"<br/>";
}
}
$obj=new A;
$obj(4);
$obj("Hello");
$obj(4.5);
echo "<b>is_callable() method is used to check whether an object can be called or not </b><br/>";
var_dump(is_callable($obj));
?>
Output:
int(4)
string(5) "Hello"
float(4.5)
is_callable() method is used to check whether an object can be called or not
bool(true)
PHP set static Method:-
In this current tutorial we will study about a new method called __set_static(), which is introduced in PHP 5. With the help of this method we can assign values to a new object dynamically. Examples will help to understand the concept
_set_static()Method in PHP :
In this tutorial we will study how to assign values of an object to another object dynamically. To do this we use __set_static() method.
We need to declare a magic method called __set_static() which is declared inside the class and by using var_export() we pass a values to it and assign the values to locally declared an object and after assigning the values we return the object.
PHP Set Static Method Example:
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($array)
{
$obj2=new A;
$obj2->var1=$array['var1'];
$obj2->var2=$array['var2'];
return $obj2;
}
}
$obj1=new A;
$obj1->var1=2010;
$obj1->var2="year";
eval('$obj3='.var_export($obj1,true).';');
var_dump($obj3);
?&?>
Output:strong>
object(A)#2 (2) { ["var1"]=> int(2010) ["var2"]=> string(4) "year" }
PHP Clone Object:-
In this PHP tutorial, we will study about cloning of object, how to make a clone object, what are the process of cloning in PHP 5 and how is it different from PHP 4
PHP Clone Objects:
Meaning of clone is that make multiple identical copies of the original one, the process of cloning in PHP 5 is quite different from PHP 4, in the earlier version of PHP all we need to do is to assign an object to another object. But in the latest version of PHP, clone construct along with a magic method is used to control the cloning process.
A clone object is created by using clone keyword which is called implicitly, and it is not possible to call the method explicitly. When an object is cloned a shallow copy of the original object is created.
After the creation of cloned object, if a __clone() method is defined,  __clone() method of the newly created object is called, to change any properties which is need to be changed.
Example:
<?php
class A{
public $var1;
static $var2=0;
public function __construct(){
$this->var1=++self::$var2;}
public function __clone(){
$this->var1=++self::$var2;}}
class B{
public $obj1;
public $obj2;
function __clone(){
$this->obj1=$this->obj2;}}
$objA=new B();
$objA->obj1=new A;
$objA->obj2=new A;
$objB=clone $objA;
print("Actual Object is:<br/>");
print_r($objA);
print("<br/>Clone Object is:<br/>");
print_r($objB);
?>
Output:
Actual Object is:
B Object ( [obj1] => A Object ( [var1] => 1 ) [obj2] => A Object ( [var1] => 2 ) )
Clone Object is:
B Object ( [obj1] => A Object ( [var1] => 2 ) [obj2] => A Object ( [var1] => 2 ) )
PHP References Explained:-
This tutorial covers three basic operations performed by references, assigning values by references, passing by references, returning by references etc. In PHP references means to access the same variable by two or more different names.
References In PHP:
What PHP References are?
In PHP references  means to access the same variable by two or more different names. References are not like  C pointers means these are not for storing address or any other pointer arithmetic. The references can be linked to hardlinking in Unix filesystem.
This tutorial covers three basic operations performed by references, assigning values by references, passing by references, returning by references etc.
Assign by reference:
PHP Reference Example:
<?php
$var1=12;
$var2=&$var1;
echo "Value of \$var1:".$var1."<br/>";
echo "Value of \$var2:".$var2."<br/>";
?>
Output:
Value of $var1:12
Value of $var2:12

Post a Comment

Blogger Tips and TricksLatest Tips And TricksBlogger Tricks

Visitors

Cloud Power For You

Website Hosting At Low Price

Contatc

Empire Views
 
Top