Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Friday, April 5, 2013

PHP Array -> Iteration

Array Iteration: List all the value one by one in an array known as array iteration.

/** Example 1 - Array Iterator **/
$array = array("one", "two", "three","four");
foreach ($array  as $data) {
    echo "$data\n";
}

/** Example 2 - Array Iterator **/ 
$array1 = array("one", "two", "three","four");
while (list(, $value) = each( $array1 ) ) {
    echo "Value: $value
\n";
} 

Object Iteration: List all public variable one by one in a class. See following examples.

class TestClass{
    public $var1 = 'Val-1';
    public $var2 = 'Val-2';
    public $var3 = 'Val-3';

    protected $protected = 'Protected Var';
    private   $private   = 'Private Var';

    function testFunction() {
       echo "TestClass::testFunction:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
       
    }
}

$class = new TestClass();
foreach($class as $key => $value) {
    print "$key => $value\n";    
}

echo "\n";
$class->testFunction();

Thursday, April 4, 2013

OOP SPL

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Read More.....

OOP -> Magic Methods

Magic Methods are methods of a class that call automatically on some situation, if they are defined within that class.


For example, if you have defined __construct in a class, whenever you create an object of that class. __construct will call automatically.

Properties of magic methods
Call automatically, if defined within that class
Start with double underscore (__)
Called implicitly
Introduce in PHP5

Following are the magic methods and their property
  • __construct() called when create instance of a class. 
  • __destruct() called when destroy the object. 
  • __call()  called when try to access a function that does not exist within class.
  • __callStatic() called when try to access a function that does not exist within class in static context.
  • __get() called when trying to get data that is not exist.
  • __set() called when trying to writing data to inaccessible properties. 
  • __isset() called when use isset / empty function on inaccessible variable.
  • __unset() called when us unset with inaccessible variable.
  • __sleep() called prior to any serialization 
  • __wakeup() called prior to any un-serialization.
  • __toString() called when echo the class object.
  • __invoke() called when a script tries to call an object as a function.  
  • __set_state() called when classes exported by var_export() since PHP 5.1.0.
  • __clone() called after using clone function.
Following are the Example of __toString magic method.
class TestClass{
    public $foo;
    public function __construct($foo) {
        $this->foo = $foo;
    }
    public function __toString()
    {
        return '__toString function called';
    }
}

$class = new TestClass('Testing');
//testing __toString magic method
echo $class;


Wednesday, April 3, 2013

OOP -> Late Static Bindings

PHP5.3 Introduce a feature that's called late static bindings which is used to reference the called class in a context of static inheritance.

class ABC {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class ABC1 extends ABC {
    public static function who() {
        echo __CLASS__;
    }
}

ABC1::test();

OOP -> Class Constants

Class constants are the constant(Never changed) declared in a class. constants are not start with ' sign and must be followed by "constant" keyword;

Example of constant
class MyClass  {
    const constant = '10';
    function showConstant() {
        echo  self::constant . "\n";
    }
}

//will print 10
echo MyClass::constant . "\n";


$obj1 = new MyClass();
//give error
echo $obj1->constant;


Rules for class constants
  • constant variable followed by constant
  • constant variables never start with $
  • constant variables can not be changed
  • constant variables can be used with scrope resolution (::) operator
  • constants variables cannot use with object

OOP -> Type Hinting


PHP5 Introduce Type Hinting, that force the method/function parameter to specific type.

Suppose you have create an function that reverse the array, and you want whenever some call your function must pass the array parameter.

In this case, type hinting will help you.

Following are the example of type hinting
function reverse(array $array ){
  rsort($array);
  return $array;  
}
$array = Array('zend','framework','200','500');
reverse($array);

OOP -> Reflection

Reflection is a property of a OOP that enable you to get the class name, description, functions name and their parameter etc.

See an example Below

class ABC {
    public $name='Arun';
    public  function test1() {
      return 'Testing Message';
    }
    public  function test2() {
      return 'Testing Message';
    }    
}

$cls = new ReflectionClass('ABC');
$methods = $cls->getMethods();
 
$fields = array();
foreach($methods as $method) {
    //Just take everything after get as the field name
    $fields[] = $method->getName();
  
}
print_r($fields);


OOp -> Autoload

Autoload: As its name denote autoload is property of a OOP that enable to load a class dynamically. It means when you create an object of class, It will called __autoload function that include file.

See in below example

function __autoload($class_name) {
    include $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 

if you have "MyClass1.php" and "MyClass2.php" in same directory, it will include automatically else will generate error.

OOP -> Static Methods & Properties

Static Methods: Method of a class that can be access by using scope resolution (i.e ::) without create the instance of that class;

Example of Static Methods
class ABC {
    public $name='Arun';
    public static function test() {
      return 'Testing Message';
    }
}
//will print the Testing Message';
echo ABC::test();
$obj = new ABC();
//will print the Testing Message';
echo $obj->test();


Following are the property of static method
  • Can be use with scope resolution operator (::)
  • Static method delcared with use of "static" keyword.
  • Need not to create the object of that class
  • Within static function, we can not use other method
  • We can use other method in static function, but need to create object to class method
  • Calling non-static methods within static function,  generates an E_STRICT level warning.

Tuesday, April 2, 2013

OOP -> Exception

Exception Handling is used to handle the error. It can handle all types of error like Warning, Notice, User defined Error message etc but unfortunately it can not handle fatal error.

We can also suppress the error with the use of  "@"  error operator. But we use exception handling so that we can show the readable error message to users.

Following are the example of exception handling.

function inverse($x) {
    if (!$x) {
        throw new Exception('Can not Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(50) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}


Try: set the statements which you want to test.
catch: If error comes, statement fall under catch

OOP -> interfaces

  • The Interfaces are abstract classes, which was declared but not defined.
  • we can not create object of Interfaces.
  • To use interfaces, we use "implements" keyword.
  • Interfaces have empty functions which you have to defined during the implement. 
  • You have to defined all the functions during the implements.
  • Interfaces are 100% blueprint that tell what function you must defined.
  • We can implements one or more class during in-heritance.
Following are the Example of Interfaces

interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

OOP -> Modifiers

Modifier =  visibility = Access Level of data member or Member function.

Modifier play very vital rule in any class.
Becuase
Some property all can acess - Public
Some property only relevant person can acess - Protected
Some property only you  can access - Private

Therefore Modifiers are three types
a) Public
b) Protected
c) Private

Data member can be three types public, protected OR private
Member function can be three types public, protected OR private.

Data Member refer to class variable.
Member function refer to class function.

Example1:


class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // It will be Works
echo $obj->protected; // Fatal Error becuase you cannot access protected in this way
echo $obj->private; // Fatal Error becuase you cannot access protected in this way
$obj->printHello(); // Shows Public, Protected and Private data meber values


Example 2:

class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // It will be Work
echo $obj2->private; // Undefined becuase private variable can not be inherit
echo $obj2->protected; // Fatal Error becuase protected can be used within function only
$obj2->printHello(); // Shows Public, Protected2, Undefined



Monday, April 1, 2013

OOP -> Instantiation

Instantiation provide a mechanism of OOP to use to class's again and again.

OR 

To use data-member or member function, we have to create an instance of the class.

Following are the example to create the object of class in different types

class Emp{
  public $totalEmp;
  function __construct($totalEmp=10){
    $this->totalEmp = $totalEmp;
  }
  function setTotalEmp($totalEmp){
    $this->totalEmp = $totalEmp;  
  }
  function getTotalEmp($totalEmp){
    return $this->totalEmp;  
  }  
}

/** first way to create obj **/
$emp1 = new Emp;
echo $emp1->totalEmp;
echo '
';

/** second way  to create obj **/
$emp2 = new Emp();
echo $emp2->totalEmp;
echo '
';

/** third way to create obj **/
$emp3 = new Emp(30);
echo $emp3->totalEmp;