Tuesday, June 28, 2011

PHP OOPs concepts

Access control modifiers 
Public:  used from anywhere in the script  Private:  only be used by the object it is part of; it cannot be accessed elsewhere  Protected:   used by the object it is part of, or descendants of that class   Final:  This variable or function cannot be overridden in inherited class/es Abstract:   This function or class  cannot be used directly - you must inherit from them first
Interfaces
Object interfaces allow you to create code which specifies which methods a class  must implement, without having to define how these methods are handled.
<?php    // Declare the interface 'iTemplate'  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;  }  }    // This will not work  // Fatal error: Class BadTemplate contains 1 abstract methods  // and must therefore be declared abstract (iTemplate::getHtml)  class  BadTemplate implements iTemplate  {  private $vars = array();    public function setVariable($name, $var)  {  $this->vars[$name] = $var;  }  }  ?>
Encapsulation
<?php    class  Hide {  private $myname;  function getmyname()  {  $myname = "damodharan";  return $myname;  }  }  class  damu {  private static $name;  public function name()  {  if( $this->name == null ) {  $this->name = new Hide();  }  return $this->name;  }  }  $run = new damu();  echo $run->name()->getmyname();  ?>
Polymorphism
<?php    class  Base  {  function mytext()  {  echo "hi am from base class ";  }  }    class  myFirstClass extends Base  {  function mytext()  {  echo "hi am from myFirstClass class ";  }  }  class  mySecondClass extends Base  {  function mytext()  {  echo "hi am from mySecondClass class ";  }  }  //create the object for the class using Polymorphism   $objects = array ( $baseIns = new Base(), $myFirstClasIns = new myFirstClass(), $mySecondClasIns = new mySecondClass()  );    foreach ($objects as $object) {  echo $object->mytext();  echo " \n";  ?>