Dieses Blog durchsuchen

Sonntag, 16. Oktober 2016

php: calling protected methods without inheritance

Sometimesyou need to call a protected method without inherit from it.
This can be done by integrating the magic method __call()

Here is an example from php.net



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();

?>

Keine Kommentare:

Kommentar veröffentlichen