Skip to content

Instantly share code, notes, and snippets.

@shameerc
Created December 27, 2010 17:37
Show Gist options
  • Select an option

  • Save shameerc/756333 to your computer and use it in GitHub Desktop.

Select an option

Save shameerc/756333 to your computer and use it in GitHub Desktop.
Basic example for create_function()
<?php
$array = array(1,2,3,4,5);
$v= 4;
$result = array_filter($array,function($n) use(&$v){return $v === $n;});
print_r($reslt);
?>
<?php
//Bad closure.
$fact = function($n) {
if($n>=1)
return 1;
else
return $n*$fact(n-1);
}
echo $fact(5); // Output : Error
?>
<?php
$factorial = function($n) use (&$factorial) {
if ($n <= 1)
return 1;
else
return $n * $factorial($n - 1);
};
echo $factorial(5); //Output : 120
?>
<?php
$sum = create_function('$a,$b','return $a+$b;');
echo $sum(2,3); //Output : 5
?>
var fact = function(n) {
if(n <= 1)
return 1;
else
return n*fact(n-1);
};
alert(fact(5)) // Output : 120
<?php
//Classic Y-combinator function
function Y($F) {
$func = function ($f) { return $f($f); };
return $func(function ($f) use($F) {
return $F(function ($x) use($f) {
$ff = $f($f);
return $ff($x);
});
});
}
//Anonymous factorial function using Y-combinator
$factorial = Y(function($fact){
return function($n) use($fact) {
if($n<=1)
return 1;
else
return $n*$fact($n-1);
};
});
echo $factorial(5); //Output : 120
?>
<?php
//Simple math class
class Math
{
function __construct($a) {
$this->a =$a;
}
//Returns a closure
function mul()
{
//We can't directly use $this inside closure
$self = $this;
return function($n) use($self) {
return $n*$self->a;
};
}
}
$math = new Math(5);
$mul = $math->mul();
echo $mul(4); //Output : 20
?>
<?php
//This class demonstrate a way of prototyping
//applications using closures
Class Hello
{
public $name;
public $methods;
Public function __call($method, $args)
{
return call_user_func_array($this->methods[$method], $args);
}
public function __set($name, $value)
{
$this->methods[$name] = $value ;
}
}
$hello= new Hello();
$hello->name = 'User';
$hello->greet = function() use ($hello) {
return 'Hello '.$hello->name;
};
echo $hello->greet(); //Output : Hello User
?>
<?php
$sum = function($a,$b) {
return $a+$b;
};
echo $sum(2,3); //Output : 5
?>
@ilikeprograms
Copy link

In array_filter_closure.php you have a typo. $reslt should be $result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment