PHP OOP Concepts
PHP OOP Concepts
PHP OOP Concepts
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. 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 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 & Destructor: 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 Constants: 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
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
Inheritance in PHP: 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 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 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 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 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: 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 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. 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 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: 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: 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 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:
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(); ?> 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 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. 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