SlideShare a Scribd company logo
1 of 29
Download to read offline
#3




Object Oriented Programming with PHP 5
More OOP
                                 Doc. v. 0.1 - 18/03/09




               Wildan Maulana | wildan [at] tobethink.com
Class Information Functions
• Checking if a Class already exists
• Finding currently loaded classes
• Finding out if Methods and Properties
  exists
• Checking the type of Class
• Finding out the Class name
Checking if a Class already exists

• You can use class_exists() function
           <?php
           include_once(quot;../ch2/emailer.class.phpquot;);
           if( class_exists(quot;Emailerquot;))
           {
              $emailer = new Emailer(quot;hasin@pageflakes.comquot;);
           }
           else
           {
              die(quot;A necessary class is not foundquot;);
           }
           ?>
Finding currently loaded Classes

• You can use get_declared_classes()
  function.
                <?php
                include_once(quot;../ch2/emailer.class.phpquot;);
                print_r(get_declared_classes());
                ?>
Finding out if Methods and Properties Exists

• You can use method_exists() and
  property_exists() functions
Checking the Type of Class
 • You can use is_a() function to check
   the type of a class
<?php
class ParentClass
{
                                                                    Its a ChildClass Type Object
}
                                                                    Its also a ParentClass Type Object
class ChildClass extends ParentClass
{
}
$cc = new ChildClass();
                                                                       output
if (is_a($cc,quot;ChildClassquot;)) echo quot;It's a ChildClass Type Objectquot;;
echo quot;nquot;;
if (is_a($cc,quot;ParentClassquot;)) echo quot;It's also a ParentClass Type
Objectquot;;
?>
Finding out the Class name
• You can use get_class() function
         <?php
         class ParentClass
         {
         }
         class ChildClass extends ParentClass
         {
         }
         $cc = new ChildClass();
         echo get_class($cc)
         ?>
Exception Handling
• One of the most improved features in PHP5 is that you can
  now use exceptions, like other OOP languages out there.
  PHP5 introduces these exception to simplify error
  management            <?php
                       //class.db.php
                       error_reporting(E_ALL - E_WARNING);
                       class db
                       {
                          function connect()
                          {
                            if (!pg_connect(quot;host=localhost password=pass user=username
                                       dbname=dbquot;)) throw new Exception(quot;Cannot connect
                                       to the databasequot;);
                          }
                       }
                       $db = new db();
                       try {
                          $db->connect();
                       }
                       catch (Exception $e)
                       {
                          print_r($e);
                       }
                       ?>
Collectiong all PHP Errors as Exception




                TODO
<?php
                            class QueryIterator implements Iterator
 Iterators                  {
                              private $result;
                              private $connection;
                              private $data;
                              private $key=0;
• An Iterator is a new        private $valid;
  command introduce in        function __construct($dbname, $user, $password)
                              {
  PHP5 to help traversing       $this->connection = pg_connect(quot;dbname={$dbname} user={$user}quot;);
                              }
  through any object          public function exceute($query)
                              {
                                $this->result = pg_query($this->connection,$query);
                                  if (pg_num_rows($this->result)>0)
                                $this->next();
                              }
                              public function rewind() {}
                              public function current() {
                                return $this->data;
                              }
                              public function key() {
                                return $this->key;
                              }
                              public function next() {
                                if ($this->data = pg_fetch_assoc($this->result))
                                {
                                   $this->valid = true;
                                   $this->key+=1;
                                }
                                else
                                $this->valid = false;
                              }
                              public function valid() {
                                return $this->valid;
                              }
                            }
                            ?>
The Code In Action

 <?php
 $qi= new QueryIterator(quot;golpoquot;,quot;postgres2quot;,quot;quot;);
 $qi->exceute(quot;select name, email from usersquot;);
 while ($qi->valid())
 {
   print_r($qi->current());
   $qi->next();
 }
 ?>
ArrayObject
• Another useful object introduced in PHP5 is ArrayObject()
  that wraps the regular PHP array and gives it an OO flavor.
  You can programmatically access the array in an OO style

        <?php
        $users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;,
           quot;afifquot;=>quot;mayflower@phpxperts.netquot;,
           quot;ayeshaquot;=>quot;florence@pageflakes.netquot;));
        $iterator = $users->getIterator();
        while ($iterator->valid())
        {
          echo quot;{$iterator->key()}'s Email address is
                {$iterator->current()}nquot;;
                $iterator->next();
        }
        ?>
ArrayObject() Methods
    Append()
•
    This method can add any value at the end of the collection
    GetIterator()
•
    This method simply creates an Iterator object and return so that you can
    perform iteration using Iteration style. This is very useful method for getting
    an Iterator object from any array
    OffsetExists()
•
    The method can determine whether the specified offset exists in the
    collection
    OffsetGet()
•
    This method returns the value for specified offset
    OffsetSet()
•
    Like offsetGet(), this method can set any value to the specified index()
    OffsetUnset()
•
    This method can unset the element at the specified index
ArrayObject() in Action

<?php
$users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;,
   quot;afifquot;=>quot;mayflower@phpxperts.netquot;,
   quot;ayeshaquot;=>quot;florence@pageflakes.netquot;));
$iterator = $users->getIterator();
while ($iterator->valid())
{
  echo quot;{$iterator->key()}'s Email address is
        {$iterator->current()}nquot;;
        $iterator->next();
}
?>
Array to Object
<?php
class ArrayToObject extends ArrayObject
{
  public function __get($key)
  {
    return $this[$key];
  }
  public function __set($key,$val)
  {
    $this[$key] = $val;
  }
}
?>

                     <?php
                     $users = new ArrayToObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;,
                       quot;afifquot;=>quot;mayflower@phpxperts.netquot;,
                       quot;ayeshaquot;=>quot;florence@pageflakes.netquot;));
                     echo $users->afif;
                     ?>
<?php
Accessing Objects in   class users implements ArrayAccess
                       {
    Array Style          private $users;
                       public function __construct()
                       {
                             $this->users = array();
                       }
                       public function offsetExists($key)
                       {
                             return isset($this->users[$key]);
                       }
                       public function offsetGet($key)
                       {
                             return $this->users[$key];
                       }
                       public function offsetSet($key, $value)
                       {
                             $this->users[$key] = $value;
                       }
                       public function offsetUnset($key)
                       {
                             unset($this->users[$key]);
                       }
                       }
                       $users = new users();
                       $users['afif']=quot;mayflower@phpxperts.netquot;;
                       $users['hasin']=quot;hasin@pageflakes.comquot;;
                       $users['ayesha']=quot;florence@phpxperts.netquot;;
                       echo $users['afif']
                       ?>
Serialization
 • Serialization is a process of persisting the state of
   an object in any location, either physical files or in
   variables.                 <?php
                                               class SampleObject
                                               {
                                                  public $var1;
                                                  private $var2;
The script will output a string, which
PHP understands how to unserialize.
                                                  protected $var3;
                                                  static $var4;
                                                  public function __construct()
                                                  {
                                                    $this->var1 = quot;Value Onequot;;
                                                    $this->var2 = quot;Value Twoquot;;
                                                    $this->var3 = quot;Value Threequot;;
                                                    SampleObject::$var4 = quot;Value Fourquot;;
                                                  }
                                               }
                                               $so = new SampleObject();
                                               $serializedso =serialize($so);
                                               file_put_contents(quot;text.txtquot;,$serializedso);
Unserialize
  <?php
  include_once(quot;sampleobject.class.phpquot;);
  $serializedcontent = file_get_contents(quot;text.txtquot;);
  $unserializedcontent = unserialize($serializedcontent);
  print_r($unserializedcontent);
  ?>


                                        Ouput

Remember : We can't save          SampleObject Object
the state of a static variables   (
by serializing                      [var1] => Value One
                                    [var2:private] => Value Two
                                    [var3:protected] => Value Three
                                  )
Magic Methods in Serialization
• PHP5 provides two magic methods to
  hook in process of serialization :
  – __sleep     <?php
                class ResourceObject
                {
  – __awake       private $resource;
                  private $dsn;
                  public function __construct($dsn)
                  {
                    $this->dsn = $dsn;
                    $this->resource = pg_connect($this->dsn);
                  }
                  public function __sleep()
                  {
                    pg_close($this->resource);
                    return array_keys( get_object_vars( $this ) );
                  }
                  public function __wakeup()
                  {
                    $this->resource = pg_connect($this->dsn);
                  }
                }
                ?>
Object Cloning
• PHP5 introduces a new approach
  while copying objects from one into
  another, which is quite different to
  PHP4.
  – PHP4 → deep copy
  – PHP5 → shallow copy
Object Cloning
<?php
                                            PHP4 Output : Hasin
$sample1 = new StdClass();
$sample1->name = quot;Hasinquot;;
$sample2 = $sample1;
$sample2->name = quot;Afifquot;;
echo $sample1->name;
                                           PHP5 Output : Afif
?>

If you wanna make deep copy in PHP5, you can use clone keyword

          <?
          $sample1 = new stdClass();
          $sample1->name = quot;Hasinquot;;
                                                     PHP5 Output : Hasin
          $sample2 =clone $sample1;
          $sample2->name = quot;Afifquot;;
          echo $sample1->name;
          ?>
Autoloading Classes or
                   Classes on Demand

• While working with big projects, another very good practice
  is loading classes only when you need it. That means you
  shouldn't over consume the memory by loading unnecessary
  classes all the time.
                               <?php
                               function __autoload($class)
                               {
                                 include_once(quot;{$class}.class.phpquot;);
                               }
                               $s = new Emailer(quot;hasin@somewherein.netquot;);
                               ?>


        Because of __autoload() function, PHP5
        will auto load a file named class.emailer.php
        in the current directory
Method Chaining
 • Method chaining is another process introduced in PHP5 by
   which you can directly access the methods and attributes of
   an object when it is returned by any function



$SomeObject­>getObjectOne()­>getObjectTwo()­>callMethodOfObjectTwo();


                        Or in a real life ....


$dbManager­>select(quot;idquot;,quot;emailquot;)­>from(quot;userquot;)­>where(quot;id=1quot;)
                                        ­>limit(1)­>result();
<?php
class DBManager
{
   private $selectables = array();
   private $table;
   private $whereClause;
   private $limit;
   public function select()
   {
     $this­>selectables=func_get_args();
     return $this;
   }
   public function from($table)
                                   ........ 
   {
                                   public function result()
     $this­>table = $table;
                                      {
     return $this;
                                        $query = quot;SELECT quot;.join(quot;,quot;,$this­>selectables).quot; FROM
   }
                                                                                {$this­>table}quot;;
   public function where($clause)
                                        if (!empty($this­>whereClause))
   {
                                        $query .= quot; WHERE {$this­>whereClause}quot;;
     $this­>whereClause = $clause;
                                        if (!empty($this­>limit))
     return $this;
                                        $query .= quot; LIMIT {$this­>limit}quot;;
   }
                                        echo quot;The generated Query is : nquot;.$query;
   public function limit($limit)
                                      }
   {
                                   }
     $this­>limit = $limit;
                                   $db= new DBManager();
     return $this;
                                   $db­>select(quot;idquot;,quot;namequot;)­>from(quot;usersquot;)­>where(quot;id=1quot;)­>
   }
                                                                            limit(1)­>result();
........
                                   ?>
  
                      The output


                                    The generated Query is :
                                    SELECT id,name FROM users WHERE id=1 LIMIT 1
Life cycle of an Object in PHP and
               Object Caching
• An object is live until the script ends. As soon as the
  script finishes executing, any object instantiated by this
  script also dies
• Unlike web tier in Java, there is no global or application-
  level scope in PHP
• But there is some object caching technology available
  for PHP, the most successful among them is memcached
  (http://danga.com/memcached.)
Using memcached
• Download and install the memcached first!

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die (quot;Could not connectquot;);
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 12364;
$memcache->set('obj', $tmp_object, false, 60*5) or die (quot;Failed to
save data at the serverquot;);
?>

 Restore the object....
                          <?php
                          $memcache = new Memcache;
                          $memcache->connect('localhost', 11211) or die (quot;Could not connectquot;);
                          $newobj = $memcache->get('obj');
                          ?>
Summary
• In this presentation we learned how to use some
  advanced OOP concepts in PHP. We learned how to
  retrieve information from any object, and learned about
  ArrayAccess, ArrayObject, Iterators, and some
  other native objects which simplifies the life of a
  developer. Another very important thing we learned is
  Exception Handling.

  In next presentation we will learn about design patterns
  and how to use them in PHP.

  Happy Learning .. @_@
Q&A
Reference
• Object Oriented Programming with
  PHP5, Hasin Hayder, PACKT Publishing

More Related Content

What's hot (20)

Php Oop
Php OopPhp Oop
Php Oop
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
Oops in php
Oops in phpOops in php
Oops in php
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Only oop
Only oopOnly oop
Only oop
 

Similar to Object Oriented Programming with PHP 5 - More OOP

PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Stephan Schmidt
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Michael Wales
 

Similar to Object Oriented Programming with PHP 5 - More OOP (20)

PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 
Oops in php
Oops in phpOops in php
Oops in php
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Magic function in PHP
Magic function in PHPMagic function in PHP
Magic function in PHP
 
Functional php
Functional phpFunctional php
Functional php
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
 

More from Wildan Maulana

Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Wildan Maulana
 
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Wildan Maulana
 
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonKetahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonWildan Maulana
 
Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Wildan Maulana
 
ICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipWildan Maulana
 
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWOpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWWildan Maulana
 
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...Wildan Maulana
 
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsPostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsWildan Maulana
 
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...Wildan Maulana
 
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpMensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpWildan Maulana
 
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity ProviderKonfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity ProviderWildan Maulana
 
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Wildan Maulana
 
Instalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpInstalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpWildan Maulana
 
River Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationRiver Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationWildan Maulana
 
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...Wildan Maulana
 
Penilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarPenilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarWildan Maulana
 
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesProyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesWildan Maulana
 
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaOpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaWildan Maulana
 
Menggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingMenggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingWildan Maulana
 

More from Wildan Maulana (20)

Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018
 
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
 
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonKetahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
 
Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014
 
ICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi Arsip
 
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWOpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
 
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
 
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsPostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
 
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
 
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpMensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
 
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity ProviderKonfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
 
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
 
Instalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpInstalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphp
 
River Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationRiver Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River Restoration
 
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
 
Penilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarPenilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan Dasar
 
Statistik Listrik
Statistik ListrikStatistik Listrik
Statistik Listrik
 
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesProyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
 
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaOpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
 
Menggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingMenggunakan AlisJK : Equating
Menggunakan AlisJK : Equating
 

Recently uploaded

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Object Oriented Programming with PHP 5 - More OOP

  • 1. #3 Object Oriented Programming with PHP 5 More OOP Doc. v. 0.1 - 18/03/09 Wildan Maulana | wildan [at] tobethink.com
  • 2. Class Information Functions • Checking if a Class already exists • Finding currently loaded classes • Finding out if Methods and Properties exists • Checking the type of Class • Finding out the Class name
  • 3. Checking if a Class already exists • You can use class_exists() function <?php include_once(quot;../ch2/emailer.class.phpquot;); if( class_exists(quot;Emailerquot;)) { $emailer = new Emailer(quot;hasin@pageflakes.comquot;); } else { die(quot;A necessary class is not foundquot;); } ?>
  • 4. Finding currently loaded Classes • You can use get_declared_classes() function. <?php include_once(quot;../ch2/emailer.class.phpquot;); print_r(get_declared_classes()); ?>
  • 5. Finding out if Methods and Properties Exists • You can use method_exists() and property_exists() functions
  • 6. Checking the Type of Class • You can use is_a() function to check the type of a class <?php class ParentClass { Its a ChildClass Type Object } Its also a ParentClass Type Object class ChildClass extends ParentClass { } $cc = new ChildClass(); output if (is_a($cc,quot;ChildClassquot;)) echo quot;It's a ChildClass Type Objectquot;; echo quot;nquot;; if (is_a($cc,quot;ParentClassquot;)) echo quot;It's also a ParentClass Type Objectquot;; ?>
  • 7. Finding out the Class name • You can use get_class() function <?php class ParentClass { } class ChildClass extends ParentClass { } $cc = new ChildClass(); echo get_class($cc) ?>
  • 8. Exception Handling • One of the most improved features in PHP5 is that you can now use exceptions, like other OOP languages out there. PHP5 introduces these exception to simplify error management <?php //class.db.php error_reporting(E_ALL - E_WARNING); class db { function connect() { if (!pg_connect(quot;host=localhost password=pass user=username dbname=dbquot;)) throw new Exception(quot;Cannot connect to the databasequot;); } } $db = new db(); try { $db->connect(); } catch (Exception $e) { print_r($e); } ?>
  • 9. Collectiong all PHP Errors as Exception TODO
  • 10. <?php class QueryIterator implements Iterator Iterators { private $result; private $connection; private $data; private $key=0; • An Iterator is a new private $valid; command introduce in function __construct($dbname, $user, $password) { PHP5 to help traversing $this->connection = pg_connect(quot;dbname={$dbname} user={$user}quot;); } through any object public function exceute($query) { $this->result = pg_query($this->connection,$query); if (pg_num_rows($this->result)>0) $this->next(); } public function rewind() {} public function current() { return $this->data; } public function key() { return $this->key; } public function next() { if ($this->data = pg_fetch_assoc($this->result)) { $this->valid = true; $this->key+=1; } else $this->valid = false; } public function valid() { return $this->valid; } } ?>
  • 11. The Code In Action <?php $qi= new QueryIterator(quot;golpoquot;,quot;postgres2quot;,quot;quot;); $qi->exceute(quot;select name, email from usersquot;); while ($qi->valid()) { print_r($qi->current()); $qi->next(); } ?>
  • 12. ArrayObject • Another useful object introduced in PHP5 is ArrayObject() that wraps the regular PHP array and gives it an OO flavor. You can programmatically access the array in an OO style <?php $users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); $iterator = $users->getIterator(); while ($iterator->valid()) { echo quot;{$iterator->key()}'s Email address is {$iterator->current()}nquot;; $iterator->next(); } ?>
  • 13. ArrayObject() Methods Append() • This method can add any value at the end of the collection GetIterator() • This method simply creates an Iterator object and return so that you can perform iteration using Iteration style. This is very useful method for getting an Iterator object from any array OffsetExists() • The method can determine whether the specified offset exists in the collection OffsetGet() • This method returns the value for specified offset OffsetSet() • Like offsetGet(), this method can set any value to the specified index() OffsetUnset() • This method can unset the element at the specified index
  • 14. ArrayObject() in Action <?php $users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); $iterator = $users->getIterator(); while ($iterator->valid()) { echo quot;{$iterator->key()}'s Email address is {$iterator->current()}nquot;; $iterator->next(); } ?>
  • 15. Array to Object <?php class ArrayToObject extends ArrayObject { public function __get($key) { return $this[$key]; } public function __set($key,$val) { $this[$key] = $val; } } ?> <?php $users = new ArrayToObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); echo $users->afif; ?>
  • 16. <?php Accessing Objects in class users implements ArrayAccess { Array Style private $users; public function __construct() { $this->users = array(); } public function offsetExists($key) { return isset($this->users[$key]); } public function offsetGet($key) { return $this->users[$key]; } public function offsetSet($key, $value) { $this->users[$key] = $value; } public function offsetUnset($key) { unset($this->users[$key]); } } $users = new users(); $users['afif']=quot;mayflower@phpxperts.netquot;; $users['hasin']=quot;hasin@pageflakes.comquot;; $users['ayesha']=quot;florence@phpxperts.netquot;; echo $users['afif'] ?>
  • 17. Serialization • Serialization is a process of persisting the state of an object in any location, either physical files or in variables. <?php class SampleObject { public $var1; private $var2; The script will output a string, which PHP understands how to unserialize. protected $var3; static $var4; public function __construct() { $this->var1 = quot;Value Onequot;; $this->var2 = quot;Value Twoquot;; $this->var3 = quot;Value Threequot;; SampleObject::$var4 = quot;Value Fourquot;; } } $so = new SampleObject(); $serializedso =serialize($so); file_put_contents(quot;text.txtquot;,$serializedso);
  • 18. Unserialize <?php include_once(quot;sampleobject.class.phpquot;); $serializedcontent = file_get_contents(quot;text.txtquot;); $unserializedcontent = unserialize($serializedcontent); print_r($unserializedcontent); ?> Ouput Remember : We can't save SampleObject Object the state of a static variables ( by serializing [var1] => Value One [var2:private] => Value Two [var3:protected] => Value Three )
  • 19. Magic Methods in Serialization • PHP5 provides two magic methods to hook in process of serialization : – __sleep <?php class ResourceObject { – __awake private $resource; private $dsn; public function __construct($dsn) { $this->dsn = $dsn; $this->resource = pg_connect($this->dsn); } public function __sleep() { pg_close($this->resource); return array_keys( get_object_vars( $this ) ); } public function __wakeup() { $this->resource = pg_connect($this->dsn); } } ?>
  • 20. Object Cloning • PHP5 introduces a new approach while copying objects from one into another, which is quite different to PHP4. – PHP4 → deep copy – PHP5 → shallow copy
  • 21. Object Cloning <?php PHP4 Output : Hasin $sample1 = new StdClass(); $sample1->name = quot;Hasinquot;; $sample2 = $sample1; $sample2->name = quot;Afifquot;; echo $sample1->name; PHP5 Output : Afif ?> If you wanna make deep copy in PHP5, you can use clone keyword <? $sample1 = new stdClass(); $sample1->name = quot;Hasinquot;; PHP5 Output : Hasin $sample2 =clone $sample1; $sample2->name = quot;Afifquot;; echo $sample1->name; ?>
  • 22. Autoloading Classes or Classes on Demand • While working with big projects, another very good practice is loading classes only when you need it. That means you shouldn't over consume the memory by loading unnecessary classes all the time. <?php function __autoload($class) { include_once(quot;{$class}.class.phpquot;); } $s = new Emailer(quot;hasin@somewherein.netquot;); ?> Because of __autoload() function, PHP5 will auto load a file named class.emailer.php in the current directory
  • 23. Method Chaining • Method chaining is another process introduced in PHP5 by which you can directly access the methods and attributes of an object when it is returned by any function $SomeObject­>getObjectOne()­>getObjectTwo()­>callMethodOfObjectTwo(); Or in a real life .... $dbManager­>select(quot;idquot;,quot;emailquot;)­>from(quot;userquot;)­>where(quot;id=1quot;)                                         ­>limit(1)­>result();
  • 24. <?php class DBManager {    private $selectables = array();    private $table;    private $whereClause;    private $limit;    public function select()    {      $this­>selectables=func_get_args();      return $this;    }    public function from($table) ........     { public function result()      $this­>table = $table;    {      return $this;      $query = quot;SELECT quot;.join(quot;,quot;,$this­>selectables).quot; FROM    }                                              {$this­>table}quot;;    public function where($clause)      if (!empty($this­>whereClause))    {      $query .= quot; WHERE {$this­>whereClause}quot;;      $this­>whereClause = $clause;      if (!empty($this­>limit))      return $this;      $query .= quot; LIMIT {$this­>limit}quot;;    }      echo quot;The generated Query is : nquot;.$query;    public function limit($limit)    }    { }      $this­>limit = $limit; $db= new DBManager();      return $this; $db­>select(quot;idquot;,quot;namequot;)­>from(quot;usersquot;)­>where(quot;id=1quot;)­>    }                                          limit(1)­>result(); ........ ?>    The output The generated Query is : SELECT id,name FROM users WHERE id=1 LIMIT 1
  • 25. Life cycle of an Object in PHP and Object Caching • An object is live until the script ends. As soon as the script finishes executing, any object instantiated by this script also dies • Unlike web tier in Java, there is no global or application- level scope in PHP • But there is some object caching technology available for PHP, the most successful among them is memcached (http://danga.com/memcached.)
  • 26. Using memcached • Download and install the memcached first! <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (quot;Could not connectquot;); $tmp_object = new stdClass; $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 12364; $memcache->set('obj', $tmp_object, false, 60*5) or die (quot;Failed to save data at the serverquot;); ?> Restore the object.... <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (quot;Could not connectquot;); $newobj = $memcache->get('obj'); ?>
  • 27. Summary • In this presentation we learned how to use some advanced OOP concepts in PHP. We learned how to retrieve information from any object, and learned about ArrayAccess, ArrayObject, Iterators, and some other native objects which simplifies the life of a developer. Another very important thing we learned is Exception Handling. In next presentation we will learn about design patterns and how to use them in PHP. Happy Learning .. @_@
  • 28. Q&A
  • 29. Reference • Object Oriented Programming with PHP5, Hasin Hayder, PACKT Publishing