__call() in PHP

By: Rob Viewed: 153195 times  Printer Friendly Format    


You can always call protected members using the __call() method - similar to how you hack around this in Ruby using send.
<?php
class Fun
{
protected function debug($message)
{
   echo "DEBUG: $message\n";
}
public function yield_something($callback)
{
   return $callback("Soemthing!!");
}
public function having_fun()
{
$self =& $this;
   return $this->yield_something(function($data) use (&$self)
   {
$self->debug("Doing stuff to the data");
// do something with $data
$self->debug("Finished doing stuff with the data.");
   });
}
// Ah-Ha!
public function __call($method, $args = array())
{
   if(is_callable(array($this, $method)))
     return call_user_func_array(array($this, $method), $args);
}
}
$fun = new Fun();
echo $fun->having_fun();
?>


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial