Thursday, November 15, 2012

Overloading methods in Php: __call()

Just for the record I know that php does not support multiple classes to be extended and today while talking to a dear friend I thought this would work to sort of workaround this, and it did, for most cases I dont think this is very useful  but if you're in college this might come in handy for a homework or project:


<?php

class Mother
{ 
  public function func2() { return 'Mother knows best'; }
}

class Father
{
  private $_aClasses;
  public function __construct()
    $this->_aClasses = array( 'Mother' => new Mother); 
  }

  public function func1() { return 'func1 from Father'; }

  public function __call($sName, $aArguments)
  {
    foreach ($this->_aClasses as $oObj)
    {
      if (method_exists($oObj, $sName))
        echo $oObj->$sName(); 
      }
      else 
        var_dump($oObj); 
      }
    }
  }
}

$oF = new Father;
$oF->func2();
?>



This outputs "Mother knows best" even thought Father doesnt have a function func2().