Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 17th, 2012  |  syntax: None  |  size: 0.94 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I run code based on the true class name of an object?
  2. if($myobject instanceof class1){
  3. }elseif($myobject instanceof class1){
  4. }
  5.        
  6. switch(get_class($myobject)){
  7.     case 'class1':
  8.        break;
  9.     case 'class2':
  10.        break;
  11. }
  12.        
  13. function objectProcessor_A($o) {}
  14. function objectProcessor_B($o) {}
  15. function objectProcessor_C($o) {}
  16.  
  17. foreach($objects AS $o) {
  18.     if(function_exist("objectProcessor_" . get_class($o)))
  19.         call_user_func("objectProcessor_" . get_class($o), $o);
  20. }
  21.        
  22. class OFactory {
  23.     static function getO($type) {
  24.         $r = new $type();
  25.         if($type === "A") {
  26.             $r.processor = function() {...};
  27.         } else if($type === "B") {
  28.             $r.processor = function() {...};
  29.         } else if($type === "C") {
  30.             $r.processor = function() {...};
  31.         }
  32.         return $r;
  33.     }
  34. }
  35.  
  36. $a = OFactory::getO("A");
  37. call_user_func($a->processor);
  38.  
  39. $b = OFactory::getO("B");
  40. call_user_func($b->processor);