With this class and method, it's possible to do nice things, like add methods on the fly to an object.
MetaTrait.php
<?php
trait MetaTrait
{
private $methods = array();
public function addMethod($methodName, $methodCallable)
{
if (!is_callable($methodCallable)) {
throw new InvalidArgumentException('Second param must be callable');
}
$this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
}
public function __call($methodName, array $args)
{
if (isset($this->methods[$methodName])) {
return call_user_func_array($this->methods[$methodName], $args);
}
throw RunTimeException('There is no method with the given name to call');
}
}
?>
test.php
<?php
require 'MetaTrait.php';
class HackThursday {
use MetaTrait;
private $dayOfWeek = 'Thursday';
}
$test = new HackThursday();
$test->addMethod('when', function () {
return $this->dayOfWeek;
});
echo $test->when();
?>
Closure::bind
(PHP 5 >= 5.4.0)
Closure::bind — Duplique une fermeture avec un nouvel objet lié et un nouveau contexte de classe.
Description
public static Closure Closure::bind
( Closure
$closure
, object $newthis
[, mixed $newscope
= 'static'
] )Cette méthode est une version statique de Closure::bindTo(). Voyez sa documentation pour plus d'informations.
Liste de paramètres
-
closure -
La fonction anonyme à lier.
-
newthis -
L'objet auquel lier la fonction anonyme ou
NULLpour délier -
newscope -
Le contexte de classe à associer à la fermeture, ou 'static' pour conserver le contexte actuel. Si un objet est utilisé, son type sera utilisé. Ceci détermine les accès protégés et privés de l'objet lié.
Valeurs de retour
Retourne un nouvel objet Closure ou FALSE si une erreur survient
Exemples
Exemple #1 Exemple Closure::bind()
<?php
class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
1 2
Voir aussi
- fonctions anonymes
- Closure::bindTo() - Duplique la fermeture avec un nouvel objet lié et un nouveau contexte de classe.
Vincius Krolow ¶
6 months ago
