Thursday 7 August 2014

OOPS Concept In PHP

OOPs (object oriented programming system) concept is use to make powerful, robust and secure programming instructions.

With any language reference there are only three basic object oriented prog concept.

  1. Encapsulation and data abstraction
  2. Inheritance
  3. Polymorphism

Advantages of OOPs

  • Real world programming
  • Ability to simulate real world event much more effectively.
  • Reusable of code
  • Information hiding
  • Programmers are able to reach their goals faster.

Object Oriented Concepts:

Lets define important terms related to Object Oriented Programming.
Class: Class is a term used in the OOP paradigm. They provide abstraction, modularity and much more to your code.
Member function: Functions created inside a class are known as member function.
Member Variable: Variables defined inside the class called member variable. These variables also called attribute of the object.
Object: Object is instance defined by your class. Define one class and create many objects of that class.  Objects are also known as instance.
Inheritance: Inheritance is most useful tools of OOP. Inheritance allows you to create one or more classes derived from a base class ( also called parent class ).
Parent class: Class inherited by another class. This is also called a base class or super class.
Child Class: A class that inherits from another class. This is also called a subclass or derived class.
Polymorphism: Poly (meaning many) and morph (meaning forms). Different behaviors for the same operation.
Overloading: Overloading means to replacing the same parental behavior in child class.
Data Abstraction: Representation of data in which the implementation details are hidden (abstracted).
Encapsulation: One of the biggest advantage of OOP is Encapsulation or data hiding. It hides the data from being accessed from outside a class directly.
Constructor: Classes with a constructor method call this method on each object creation, initialization that the object may need before it is used.
Destructors: Function which will be called automatically whenever an object is deleted or goes out of scope.

Structuring Classes

Creating a class is very simple and easy declaring a class using class keyword followed by the name of that class.
<?php class myFirstClass { #code } ?>
<?php
   class myFirstClass {
       #code
   }
?>
This is how you can create a class and insert your code inside it.
Member function
<?php class myFirstClass { function myFunction(){ echo "function 1"; } } ?>
1
2
3
4
5
6
7
<?php
   class myFirstClass {
 function myFunction(){
           echo "function 1";
       }
   }
?>


Member Variable:
<?php class myFirstClass { $var1 = "hello"; $var2; } ?>
1
2
3
4
5
6
<?php
   class myFirstClass {
       $var1 = "hello";
       $var2;
   }
?>
Creating Objects in PHP
Once you created you class now create that class object as many as you want.
<?php $objc1 = new myFirstClass(); $objc2 = new myFirstClass(); ?>
1
2
3
4
<?php
$objc1 = new myFirstClass();
$objc2 = new myFirstClass();
?>
This is how we create an object of a class.
Calling member function of a class
<?php $obj = new myFirstClass(); // object of the class $obj->myFunction(); // member function call ?>
1
2
3
4
5
<?php
 $obj = new myFirstClass(); // object of the class
 $obj->myFunction(); // member function call
?>

Inheritance

PHP class can be inherited from a parent class by using extends keyword syntax as below.
<?php class myFirstClass { function myFunction(){ echo "function 1"; } } class childClass extends myFirstClass { #code } ?>
1
2
3
4
5
6
7
8
9
10
11
12
<?php
   class myFirstClass {
       function myFunction(){
           echo "function 1";
       }
   }
   class childClass extends myFirstClass  {
       #code
   }
?>
The child class (or subclass or derived class) has these characteristics
1. Member variable declaration.
2. Same member functions as the parent and all work same as parent work.
Here childClass is the the Child Class of Parent Class myFirstClass.

ReadMore...

Polymorphism

Polymorphism means different behavior for same operation like animal talk behavior is same talk but sound is different from all animals.
class animalClass { protected $name; public function __construct($animalName) { $this->name = $animalName; } public function getName() { return $this->name; } public function talk() { return $this->getName().' is talking <br />'; } } class dogClass extends animalClass { public function getName() { return 'Dog: '.parent::getName(); } } $a = new dogClass("My dog"); echo $a->talk(); $b = new animalClass("some Cat"); echo $b->talk();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class animalClass {
     protected $name;
     public function __construct($animalName)
     {
     $this->name = $animalName;
     }
     public function getName()
     {
     return $this->name;
     }
     public function talk()
     {
     return $this->getName().' is talking <br />';
     }
  }
  class dogClass extends animalClass
  {
     public function getName()
     {
     return 'Dog: '.parent::getName();
     }
  }
$a = new dogClass("My dog");
echo $a->talk();
$b = new animalClass("some Cat");
echo $b->talk();
Different animals different voice but same method talk.

Overloading

Method overloading is where a class has two or more functions of the same name, but accepting a different number and/or data types of parameters.
In PHP, overloading means you can add object members at run-time, by implementing some of the magic methods like __set, __get, __call etc.
class myClass { public function __call($method, $args) { if ($method === 'myFunction') { echo 'Sum is calculated to ' . $this->getSum($args); } else { echo "Called method $method"; } } private function getSum($args) { $sum = 0; foreach ($args as $arg) { $sum += $arg; } return $sum; } } $obj = new myClass; $obj->myFunction(10,25,30,12); $obj->myFunction(21,20,1);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class myClass {
   public function __call($method, $args) {
       if ($method === 'myFunction') {
           echo 'Sum is calculated to ' . $this->getSum($args);
       } else {
           echo "Called method $method";
       }
   }
   private function getSum($args) {
       $sum = 0;
       foreach ($args as $arg) {
           $sum += $arg;
       }
       return $sum;
   }
}
$obj = new myClass;
$obj->myFunction(10,25,30,12);
$obj->myFunction(21,20,1);
Encapsulation

Encapsulation hides data being accessed from outside a class directly.
There is 3 types in encapsulation:
Public Members:
Its a default state of methods and properties of a class, can be accessed outside the class, within the class and in an other class that implements the class.
If you wish to limit the accessibility of the members of a class then you define class members as private or protected.
Private Members:
By describing a member private you limit it to be accessed to the class in which it is declared. A class member can be made private by using private keyword in front of the member.
<?php class myFirstClass { function myFunction(){ echo "public one"; } private function myPrivateFunction(){ echo "I'm not visible outside!"; } } ?>
1
2
3
4
5
6
7
8
9
10
<?php
   class myFirstClass {
       function myFunction(){
           echo "public one";
       }
       private function myPrivateFunction(){
           echo "I'm  not visible outside!";
       }
   }
?>
If any class extends this class not able to access myPrivateFunction just because of its a private property of this class.
Protected Members:
A class with protected property or method can be accessible within the class and it can be accessed in the class which extends that class. A class member can be made protected by using protected keyword infront of the member.
<?php class myFirstClass { function myFunction(){ echo "public one"; } protected function myprotectedFunction(){ echo "I'm visible in child class!"; } } ?>
Constructor Functions:

Constructor function is a function which called when object created of the class. So we can use this to take its advantage and initialize many things on object creation.
<?php class myFirstClass { __construct($par1, $par2){ $this->price = $par1; $this->title = $par2; } function myFunction(){ echo $this->price." ".$this->title; } } $obj = new myFirstClass('Hello',7); $obj->myFunction(); ?>
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
   class myFirstClass {
       __construct($par1, $par2){
           $this->price = $par1;
           $this->title = $par2;
       }
       function myFunction(){
           echo $this->price." ".$this->title;
       }
   }
   $obj = new myFirstClass('Hello',7);
   $obj->myFunction();
?>
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Destructor:

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor.
So that’s all for today’s tutorial and I hope it helps the and please don’t forget to give me your feedback.

Class


  • Class is a blueprint of related data members(proerties/variable) and methods(function).
  • Classes are the fundamental construct behind oops.
  • Class is a self contained independent collection of variables and functions, which work together to perform one or more specific related task.
Note: Variables within a class are called properties and functions are called methods

How to initialize a class

Class always start with "class" name. After this write class name without parentheses.

Syntax

class demo
{
 code to be executed
}

Example 1

<?php
class demo
{
function add()
 {   
    $x=800;
    $y=200;
    $sum=$x+$y;
    echo "sum of given no=".$sum."<br/>";
 }
function sub()
{
$x=1000;
$y=200;
$sub=$x-$y;
echo "Sub of given no=".$sub;
}
  }
 ?>

What is Objects

  • Object is the instance of the class.
  • Once a class has been defined, objects can be created from the class through "new" keyword.
  • class methods and properties can directly be accessed through this object instance.
  • Dot operator(->) symbol used to connect objects to their properties or methods.
Note: You can not access any property of the class without their object>

Syntax


$obj= new demo();

Example 1

<?php
class demo
{
function add()
 {   
    $x=800;
    $y=200;
    $sum=$x+$y;
    echo "sum of given no=".$sum."<br/>";
 }
function sub()
{
$x=1000;
$y=500;
$sub=$x-$y;
echo "Sub of given no=".$sub;
}
  }
  $obj= new demo();
  $obj->add();
  $obj->sub();
 ?>


  Output :   Sum=1000
                Subtraction=500


Example 2 (Parametrized Function)


<?php
class demo
{
function add($a,$b)
 {   
    $sum=$a+$b;
    echo "Sum=".$sum."<br/>";
 }
function sub($x,$y)
{
$sub=$x-$y;
echo "Subtraction=".$sub;
}
  }
  $obj= new demo();
  $obj->add(800,200);
  $obj->sub(1000,500);
 ?>


  Output :   Sum=1000
                Subtraction=500

Example 3 (Make Dynamic )


<?php
class demo
{
function add($a,$b)
 {   
    $sum=$a+$b;
    echo "Sum=".$sum."<br/>";
 }
function sub($x,$y)
{
$sub=$x-$y;
echo "Subtraction=".$sub;
}
  }
  $obj= new demo();
  $obj->add($_GET['f'],$_GET['s']);
  $obj->add($_GET['f'],$_GET['s']);
 ?>
 
 <form>
Enter first number<input type="text" name="f"/><hr/>
Enter second number<input type="text" name="s"/><hr/>
<input type="submit" value="Show result"/>
</form>


  Output :        Sum=1500
                     Subtraction=500
      Enter first number
      Enter second number
             

this keyword


To access or change a class method or property within the class itself, it's necessary to prefix thecorresponding method or property name with "$this" which refers to this class.

Access class properties inside method

Example 1

<?php
   class demo
{
         var $first=1000;
         var $second=500;
function add()
 {   
   $add=$this->first + $this->second;
    echo "addition=".$add."<br/>";
 }
function sub()
{
$sub=$this->first - $this->second;
echo "Subtractino=".$sub;
}
  }
   $obj= new demo();
   $obj->add();
   $obj->sub();

 ?>


Output : addition=1500
           Subtraction=500


Example 2

<?php
   class demo
{
         var $first=1000;
         var $second=500;
function add()
 {   
   $add=$this->first + $this->second;
    echo "addition=".$add."<br/>";
 }
function sub()
{
$sub=$this->first - $this->second;
echo "Subtractino=".$sub;
}
  }
   $obj= new demo();
   $obj->add();
   $obj->sub();

 ?>


Output : addition=1500
           Subtraction=500

Constructor


If a class name and function name will be similar in that case function is known as constructor.Constructor is special type of method because its name is similar to class name.Constructor automatically calls when object will be initializing.

Example 1
<?php
class A
{
 function testA()
{
echo "This is test method of class A";
}
function A()
{
echo "this is constructor of class A";
}
}
$obj= new A();
$obj->testA();
?>

Note : Here we have called testA() method but we didn't call A() method because it automatically called when object is initialized.

Predefine Constructor

Php introduce a new functionality to define a constructor i.e __construct().By using this function we can define a constructor. it is known as predefined constructor.Its better than user defined constructor because if we change class name then user.defined constructor treated as normal method.
Note: if predefined constructor and user defined constructor, both define in the same class, then predefined constructor work properly while user defined constructor treated as normal method.

Example 2
<?php
class A
{
function A()
{
echo "user defined constructor";
}
function __construct()
{
echo "predefined constructor";
}
}
$obj= new A();
?>


Initialize class property using constructor


Example 3
<?php
Class demo
{

Public $first;
Public $second;

Function __construct()
{
$this->first=500;
$this->second=500;
}

Function add()
{
$add=$this->first+$this->second;
Echo "sum of given no=".$add;
}

}
$obj= new demo;
$obj->add();
?>


Parameterized constructor:


Example 4
<?php
Class employee
{

Public $name;
Public  $profile;

Function __construct($n,$p)
{
$this->name=$n;
$this->profile=$p;
Echo "Welcome  "."<br/>";
}

Function show()
{
Echo $this->name."... ";
Echo "Your profile is ".$this->profile."<br/>";
}
}

$obj= new employee("ritu","Sr. Software developer");
$obj->show();

$obj1= new employee("rituraj","Tester");
$obj1->show();
?>

Destructor


The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
Note : _ _destruct() is used to define destructor.

Example 1
<?php
class demo
{
function  __construct()
{
echo  "object is initializing their propertie".<br/>";
}

function work()
{
echo  "Now works is going "."<br/>";
}

function __destruct()
{
echo  "after completion the work,  object  destroyed automatically";
}
}

$obj= new demo();
$obj->work();

//to check object is destroyed or not
echo is_object($obj);
?>

Encapsulation


Encapsulation : It is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation And hiding the essential internal property of that module known as data abstraction.

Example 1
<?php
class person
{
public $name;
public $age;
function __construct($n, $a)
{
$this->name=$n;
$this->age=$a;
}
public function setAge($ag)
{
$this->ag=$ag;
}
public function display()
{
echo  "welcome ".$this->name."<br/>";
return $this->age-$this->ag;
}
}
$person=new person("Pankaj",25);
$person->setAge(20);
echo "You are ".$person->display()." years old";
?>

Inheritance


Inheritance : Inheritance is a mechanism of extending an existing class by inheriting a class we create a new class with all functionality of that existing class, and we can add new members to the new class.
When we inherit one class from another we say that inherited class is a subclass and the class who has inherit is called parent class. We declare a new class with additional keyword extends.
Php supports multilevel inheritance .(not support multiple)

Example 1
<?php
class BaseClass
{
function add()
{
$x=1000;
$y=500;
$add=$x+$y;
echo "Addition=".$add."<br/>";
}
}

class chld extends BaseClass
{
function sub()
{
$x=1000;
$y=500;
$sub=$x-$y;
echo "subtraction=".$sub."<br/>";
 }
}

class Nestedchld extends chld
{
function mult()
{
$x=1000;
$y=500;
$mult=$x*$y;
echo "multiplication=".$mult."<br/>";
}
}

class show extends Nestedchld
{
function __construct()
{
parent::add();
parent::sub();
parent::mult();
}
}

$obj= new show();

?>


Example 2
<?php
class person
{

var $name;
var $address;
var $phone;

function printPersonInf()
{
echo $this->name;
echo $this->address;
echo $this->phone;
}
}

class employee extends person
{

var $occupation;
var $com_name;
var $buss_phone;
function printempInfo()
{
parent:: printPersonInf();
echo $this->occupation;
echo $this->com_name;
echo $this->buss_phone;
}
}

$obj= new person();
$emp=new employee();

echo $emp->name="ritu"."<br/>";
echo $emp->address="new delhi"."<br/>";
echo $emp->phone="8285431670"."<br/>";
echo $emp->occupation="Sr.Software Developer"."<br/>";
echo $emp->comp_name="ABC"."<br/>";
echo $emp->buss_phone="8285431670"."<br/>";
?>

Access modifier


Access Modifier : Access modifier allows you to alter the visibility of any class member(properties and method). In php 5 there are three scopes for class members.
  1. Public
  2. Protected and
  3. Private

Public : Public access modifier is open to use and access inside the class definition as well as outside the class definition.

Example 1
<?php
class demo
{
public $name="raj";
function disp()
{
echo $this->name."<br/>";
}
}
class child extends demo
{
function show()
{
echo $this->name;
}
}
$obj= new child;
echo $obj->name."<br/>";
$obj->disp();
$obj->show();
?>

Protected : Protected is only accessible within the class in which it is defined and its parent or inherited classes.

Example 1
<?php
class demo
{
protected $x=500;
protected $y=500;

function add()
{
echo $sum=$this->x+$this->y."<br/>";
}
function sub()
{
echo $sub=$this->x-$this->y."<br/>";
}
}
class child extends demo
{
function mult()
{
echo $mult=$this->x*$this->y;
}
}
$obj= new child;
$obj->add();
$obj->sub();
$obj->mult();
?>

Private: Private is only accessible within the class that defines it.( it can't be access outside the class means in inherited class).

Example 1
<?php
class demo
{
private $name="ritu";
public function add()
{
echo $this->name."<br/>";
}
private function sub()
{
echo "This is private method of parent class";
}
}
class child extends demo
{
function show()
{
echo $this->name;
}
}
$obj= new child;
echo $obj->name."<br/>";
$obj->disp();
$obj->show();
?>

final class


Final : The final keyword prevents child classes from overriding a method by prefixing the definition with final.

Example 1
<?php
class A
{
final function show($x,$y)
{
$sum=$x+$y;
echo "Sum of given no=".$sum;
 }
}

elass B extends A
{
function show($x,$y)
{
$mult=$x*$y;
echo "Multiplication of given no=".$mult;
 }
}

$obj= new B();
$obj->show(100,100);
?>


If the class itself is being defined final then it can't be extended.


Example 1
<?php
final Class A
{
 function show($x,$y)
{
$sum=$x+$y;
echo "Sum of given no=".$sum;
 }
}
class B extends A
{
  function show($x,$y)
{
$mult=$x*$y;
echo "Multiplication of given no=".$mult;
 }
}

$obj= new B();
$obj->show(100,100);
?>

abstract class Vs interface


  1. Abstract classes cannot be instantiated,
  2. They start with keyword abstract before the class name,
  3. One can force the methods to be declared in the inheriting class by creating abstract functions
  4. only abstract class can have abstract methods

eg.
<?php
  abstract class a
{
abstract function b();
public function c()
{
echo "Can be used as it is";
}
}
class m extends a
{
public function b()
{
echo "Defined function b<br/>";
}
}
$tClass = new m();
$tClass->b();
$tClass->c();
?>

Output : Defined function b
 Can be used as it is

Magic Methods


Magic methods provide hooks into special PHP behavior. Unlike the constants earlier, their names are written in lower/camel-case letters with two leading underscores .

Name
Description
__construct
__construct( ) is magic method which PHP invokes to create object instances of your class. It can accept any number of arguments.
__destruct
__destruct( ) method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is commonly used to perform any clean up operations that may be needed such as closing a database connection.
__get
__get( ) method if a property is undefined (or inaccessible) and called in a getter context. The method accepts one argument, the name of the property. It should return a value which is treated as the value of the property.
__set
__set( ) method is called for undefined properties in a setter context. It accepts two arguments, the property name and a value.


Description


__construct( ) is magic method which PHP invokes to create object instances of your class. It can accept any number of arguments.

<?php
   class MySample
      {
public function __construct($foo)
{
echo __CLASS__ . " constructor called with $foo.";
}
     }
$obj = new MySample(40);
// MySample constructor called with 40
 ?>
 



__destruct( ) method is called when the object is destroyed by PHP's garbage collector

<?php
   class MySample
{
public function __destruct()
{
echo __CLASS__ . " destructor called.";
}
}
$obj = new MySample; // MySample destructor called

$obj = new MySample(40);
// MySample constructor called with 40
 ?>
 



__get( ) and __set( )

<?php
   class MySample
{
private $myArray = array();
public function __set($prop, $value)
{
$this->myArray[$prop] = $value;
}

public function __get($prop)
{
return $this->myArray[$prop];
}

public function __isset($prop)
{
return isset($this->myArray[$prop]);
}

public function __unset($prop)
{
unset($this->myArray[$prop]);
}

public function __toString()
{
return __CLASS__ . ":" . $this->name;
}
}
$obj = new MySample();
if (!isset($obj->name)) {
$obj->name = "Shikha";
}
echo $obj->name; // Shikha
echo $obj; // MySample:Shikha
 ?>

No comments:

Post a Comment

Printing first 50 Fibonacci numbers Using PHP Program

Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers. For example. 0 , 1 , 1 , 2 , 3 , 5...