PHP-Object -Oriented-Concepts

PHP    Object     Oriented       Concepts    :

Before we go in detail, lets define important terms related to Object Oriented Programming :

·        Class: This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
·        Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
·        Member Variable: These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
·        Member function: These are the function defined inside a class and are used to access object data.
·        Inheritance: When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
·        Parent class: A class that is inherited from 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: This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
·        Overloading: a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
·        Data Abstraction: Any representation of data in which the implementation details are hidden (abstracted).
·        Encapsulation: refers to a concept where we encapsulate all the data and member functions together to form an object.
·        Constructor: refers to a special type of function which will be called automatically whenever there is an object formation from a class.
·        Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.


Example  1 (Accessing Member Variable) :

 <?php
class  room
{

var $str="hello"; //member variable

}

$obj=new  room();
echo $obj->str; //accessing member variable
?>

output:

hello

Example  2 (Accessing Member Function) :


<?php
class  room
{

var $length;
var $width;
var $area;

function area($a,$b)  //member function
{
$this->length=$a;
$this->width=$b;
$this->area=$this->length*$this->width;
echo "area is =".$this->area;
}
}
$obj=new  room();
$obj->area(10,20); //accessing member function

?>

ouput:
area is 200

Example  3 :

Here is an example which defines a   class of   Books     type  :


<?php
class  Books{
    /* Member variables */
    var $price;
    var $title;
    /* Member functions */
    function setPrice($par)
{
       $this->price = $par;
    }
    function getPrice(){
       echo $this->price ."<br/>";
    }
    function setTitle($par){
       $this->title = $par;
    }
    function getTitle(){
       echo $this->title ." <br/>";
    }
}
?>
The variable $this is a special variable and it refers to the same object ie.  itself.


Creating   Objects   In  PHP  :

 

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they will have their existance separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books  by  calling  member  functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
 
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

 

Constructor   Functions   :

 

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function   called __construct()   to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ){
   $this->price = $par1;
   $this->title = $par2;
}

 

 

Destructor   :

 

Like a constructor function you can define a destructor function using function __destruct().  You can release all the resourceses with-in a destructor.
Example for constructor & Destructor  :

<?php
class   example
{

function   __construct()
{

echo "constructor is called & object  is created";
echo "<br>";

}

Function  __destruct()
{

echo "destructor is called & object is free";

}
}
$obj=new  example();

?>

Inheritance   :

 

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows:
class Child extends Parent {
     <definition body>
  }
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:
·        Automatically has all the member variable declarations of the parent class.
·        Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

<?php

class   parent1

{

var $name="test";
var $phone="123456";

public function disp()
{

echo $this->name;
echo "<br>";
echo $this->phone;

echo "<br>";

}
}

class   inheritance1  extends parent1
{

function read()
{

echo "it is working fine";

}


}

$obj=new   inheritance1();

$obj->disp();

$obj->read();


?>

How   to call   parent   class   constructor          parent::__construct();   :
<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct()
   {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

//$obj = new BaseClass();
$obj = new SubClass();
?>


Function     Overriding  :

 

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

<?php
class abc
{
var $a;
var $b;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;
$sum=$this->a+$this->b;
echo"it is addition of two parameters".$sum;
}
}
class xyz extends abc
{
var $a;
var $b;
var $c;
var $d;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;

$sum=$this->a*$this->b;
echo"multiplication of two parameters".$sum;
}

}
$obj=new xyz();
$obj->cal(5,2);

?>



Function           Overloading   using    function __call:

<?Php

 

Class Test12

 

{

    Public Function __call($Name, $Arguments)

               

    {

        If ($Name === 'Test'){

            If(Count($Arguments) === 1 ){

                Return $This->Test1($Arguments[0]);

            }

            If(Count($Arguments) === 2){

                Return $This->Test2($Arguments[0], $Arguments[1]);

            }

                                                If(Count($Arguments) === 3){

                Return $This->Test3($Arguments[0], $Arguments[1],$Arguments[2]);

            }

 

        }

    }

 

    Private Function Test1($Data1)

    {

       Echo $Data1;

    }

 

    Private Function Test2($Data1,$Data2)

    {

       Echo $Data1.' '.$Data2;

    }

                 Private Function Test3($Data1,$Data2,$Data3)

    {

       Echo $Data1.' '.$Data2.$Data3;

    }

}

 

$Test = New Test12();

 

$Test->Test('One Argument');                //Echoes "One Argument"

 

$Test->Test('Two','Arguments');

 

$Test->Test('Three','Om','Test');          //Echoes "Two Arguments"

 

 

?>

 

Public Members   :

 

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:
·        From outside the class in which it is declared
·        From within the class in which it is declared
·        From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to   limit   the   accessibility    of    the    members   of   a   class   then    you    define   class      members    as    private.
<?php
class  books
{

var  $bookname;
var  $price;

function display($name, $cost)
{
echo $this->bookname=$name;
echo '<br>';
echo $this->price=$cost;
echo '<br>';

}
}

$obj=new books();
$obj->display("om",10);
?>

Interfaces   :

 

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to theri requirements. You can say, interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like   this  :

interface Mail {
   public function sendMail();
}

Then, if another class implemented that interface, like   this :

class Report implements Mail {
   // sendMail() Definition goes here
}
Example :
<?php

interface  test

{

function disp();

}

class  hello implements test
{


function disp()
{


echo "it is interface function";


}


}

$obj=new  hello();


$obj->disp();


?>

Constants   :


A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of   MyClass  :

class MyClass {
   const requiredMargin = 1.7;
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}

Class      Constants  :

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
Example : Defining and using a constant
<?php
class MyClass
{
    const constant = 'constant value';
 
    function showConstant() {
        echo  self::constant . "\n";
    }
}
 
echo MyClass::constant . "\n";
 
$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

Abstract   Classes  :

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this :
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibillity.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Example :
<?php

abstract        class       Animal
{
    public $name;
    public $age;
   
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";   
    }
   
    abstract public function Greet();
}

class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";   
    }
   
   
}

$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();

?>

Static         Keyword    :   

 

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static   can   not   be accessed with an instantiated class object (though a static method can).
Example :
<?php

Class  staticexample
{

public   static   $name="om";           // static variable


public static function disp()      //static member function


{

echo "static member function is this";


}


}


$obj=new   staticexample();


print  staticexample::$name;       // accessing static variable

echo "<br>";

staticexample::disp();            //accessing static member function





?>

Final    Keyword   :

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called<br>";
   }
  
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called<br>";
   }
}
 
class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called<br>";
   }
}
?>
Parent    keyword   :
<?php
class A
{
    function example()
           {

        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A  {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b =new B;


// This will call B::example(),    which will in turn call A::example().


$b->example();

?>

Comments

Popular posts from this blog

PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies

3 Best Applications that Organize your Chat and Messaging Accounts

Japan Style: Architecture Interiors Design