create_function
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
create_function — 文字列のコードを評価し、動的に関数を作成する
この関数は PHP 7.2.0 で 非推奨 になり、PHP 8.0.0 で 削除 されました。この関数に頼らないことを強く推奨します。
説明
指定したパラメータにより動的に関数を作成し、その関数のユニークな名前を返します。
パラメータ
通常、args
には、シングルクオートで括った文字列 を
指定することが推奨されます。
ダブルクオート を使用した場合には、\$somevar
のように変数名を
注意深くエスケープする必要があります。
args
-
関数の引数を、カンマ区切りの文字列で指定します。
code
-
関数のコード。
戻り値
一意な関数名を表す文字列を返します。
失敗した場合に false
を返します。
返される名前には、
印字できない文字("\0"
)
が含まれているので注意して下さい。
よって、この名前を出力したり、
他の文字列に組み込む場合は特別な注意を払うべきです。
例
例1 create_function() や無名関数を使い、動的に関数を作成する
(たとえば) 実行時に取得した情報をもとにして関数を作成するために、動的に作成した関数が使えます。まず create_function() を使ってみます:
<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo $newfunc(2, M_E) . "\n";
?>
同じコードは、無名関数 でも実現できます。コードや引数は、文字列に含まれていない点に注意して下さい:
<?php
$newfunc = function($a,$b) { return "ln($a) + ln($b) = " . log($a * $b); };
echo $newfunc(2, M_E) . "\n";
?>
上の例の出力は以下となります。
ln(2) + ln(2.718281828459) = 1.6931471805599
例2 create_function() や無名関数を使い、一般的な処理を行う関数を作成する
もしくは、パラメータリストに一連の処理を行うことができる 一般的なハンドラ関数を定義できます:
<?php
function process($var1, $var2, $farr)
{
foreach ($farr as $f) {
echo $f($var1, $var2) . "\n";
}
}
// 数学関数群を作成します
$farr = array(
create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
create_function('$a,$b', 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}'),
create_function('$a,$b', "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);"),
create_function('$a,$b', 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }')
);
echo "\nUsing the first array of dynamic functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);
// 文字列処理関数群を作成します
$garr = array(
create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
create_function('$a,$b', 'return "CRCs: " . crc32($a) . ", ".crc32($b);'),
create_function('$a,$b', 'return "similar(a,b) = " . similar_text($a, $b, $p) . "($p%)";')
);
echo "\nUsing the second array of dynamic functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>
ここでも、 同じことが 無名関数 で実現できます。 変数名をエスケープする必要がないことに注意して下さい。 なぜなら、文字列に埋め込まれていないからです。
<?php
function process($var1, $var2, $farr)
{
foreach ($farr as $f) {
echo $f($var1, $var2) . "\n";
}
}
// 数学関数群を作成します
$farr = array(
function($x,$y) { return "some trig: ".(sin($x) + $x*cos($y)); },
function($x,$y) { return "a hypotenuse: ".sqrt($x*$x + $y*$y); },
function($a,$b) { if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;} },
function($a,$b) { return "min(b^2+a, a^2,b) = " . min($a*$a+$b, $b*$b+$a); },
function($a,$b) { if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; } }
);
echo "\nUsing the first array of dynamic functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);
// 文字列処理関数群を作成します
$garr = array(
function($b,$a) { if (strncmp($a, $b, 3) == 0) return "** \"$a\" " .
"and \"$b\"\n** Look the same to me! (looking at the first 3 chars)"; },
function($a,$b) { return "CRCs: " . crc32($a) . ", ".crc32($b); },
function($a,$b) { return "similar(a,b) = " . similar_text($a, $b, $p) . "($p%)"; }
);
echo "\nUsing the second array of dynamic functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>
上の例の出力は以下となります。
Using the first array of dynamic functions parameters: 2.3445, M_PI some trig: -1.6291725057799 a hypotenuse: 3.9199852871011 b*a^2 = 4.8103313314525 min(b^2+a, a^2,b) = 8.6382729035898 ln(a)/b = 0.27122299212594 Using the second array of dynamic functions ** "Twas the night" and "Twas brilling and the slithy toves" ** Look the same to me! (looking at the first 3 chars) CRCs: 3569586014, 342550513 similar(a,b) = 11(45.833333333333%)
例3 動的な関数をコールバック関数として使う
おそらく、動的な関数のもっとも一般的な用途は、コールバックに渡すことでしょう。 たとえば array_walk() あるいは usort() などで使用します。
<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>
無名関数 を使うと、下記のようになります:
<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, function(&$v,$k) { $v = $v . "mango"; });
print_r($av);
?>
上の例の出力は以下となります。
Array ( [0] => the mango [1] => a mango [2] => that mango [3] => this mango )
create_function() を使い、文字列を長いものから短いものに並べます:
<?php
$sv = array("small", "a big string", "larger", "it is a string thing");
echo "Original:\n";
print_r($sv);
echo "Sorted:\n";
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
?>
無名関数 を使うと、下記のようになります:
<?php
$sv = array("small", "a big string", "larger", "it is a string thing");
echo "Original:\n";
print_r($sv);
echo "Sorted:\n";
usort($sv, function($a,$b) { return strlen($b) - strlen($a); });
print_r($sv);
?>
上の例の出力は以下となります。
Original: Array ( [0] => small [1] => a big string [2] => larger [3] => it is a string thing ) Sorted: Array ( [0] => it is a string thing [1] => a big string [2] => larger [3] => small )
User Contributed Notes 22 notes
Whilst it was correct 11 years ago, the statement of Dan D is not so correct any moreю Anonymous functions are now objects of a class Closure and are safely collected by garbage collector.
Beware when using anonymous functions in PHP as you would in languages like Python, Ruby, Lisp or Javascript. As was stated previously, the allocated memory is never released; they are not objects in PHP -- they are just dynamically named global functions -- so they don't have scope and are not subject to garbage collection.
So, if you're developing anything remotely reusable (OO or otherwise), I would avoid them like the plague. They're slow, inefficient and there's no telling if your implementation will end up in a large loop. Mine ended up in an iteration over ~1 million records and quickly exhasted my 500MB-per-process limit.
In regards to the recursion issue by info at adaniels dot nl
Anon function recursion by referencing the function variable in the correct scope.
<?php
$fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func($GLOBALS["fn2"], ++$a);');
$fn2(1);
?>
Try this to boost performance of your scripts (increase maxCacheSize):
<?php
runkit_function_copy('create_function', 'create_function_native');
runkit_function_redefine('create_function', '$arg,$body', 'return __create_function($arg,$body);');
function __create_function($arg, $body) {
static $cache = array();
static $maxCacheSize = 64;
static $sorter;
if ($sorter === NULL) {
$sorter = function($a, $b) {
if ($a->hits == $b->hits) {
return 0;
}
return ($a->hits < $b->hits) ? 1 : -1;
};
}
$crc = crc32($arg . "\\x00" . $body);
if (isset($cache[$crc])) {
++$cache[$crc][1];
return $cache[$crc][0];
}
if (sizeof($cache) >= $maxCacheSize) {
uasort($cache, $sorter);
array_pop($cache);
}
$cache[$crc] = array($cb = eval('return function('.$arg.'){'.$body.'};'), 0);
return $cb;
}
?>
In the process of migrating a PHP4 codebase to PHP5, I ran into a peculiar problem. In the library, every class was derived from a generic class called 'class_container'. 'class_container' contained an array called runtime_functions and a method called class_function that was as follows:
<?php
function class_function($name,$params,$code) {
$this->runtime_functions[$name] = create_function($params,$code);
}
?>
In a subclass of class_container, there was a function that utilized class_function() to store some custom lambda functions that were self-referential:
<?php
function myfunc($name,$code) {
$this->class_function($name,'$theobj','$this=&$theobj;'.$code);
}
?>
In PHP4, this worked just fine. The idea was to write blocks of code at the subclass level, such as "echo $this->id;", then simply $MYOBJ->myfunc("go","echo $this->id;"); and later call it like $MYOBJ->runtime_functions["go"]();
It essentially worked exactly like binding anonymous functions to objects in Javascript.
Note how the "$this" keyword had to be manually redefined for the $code block to work.
In PHP5, however, you can't redeclare $this without getting a fatal error, so the code had to be updated to:
<?php
function myfunc($name,$code) {
$this->class_function($name,'$this',$code);
}
?>
Apparently create_function() allows you to set $this via a function argument, allowing you to bind anonymous functions to instantiated objects. Thought it might be useful to somebody.
Note that using __FUNCTION__ in a an anonymous function, will always result '__lambda_func'.
<?php
$fn = create_function('', 'echo __FUNCTION__;');
$fn();
// Result: __lambda_func
echo $fn;
// Result: ºlambda_2 (the actual first character cannot be displayed)
?>
This means that a anonymous function can't be used recursively. The following code (recursively counting to 10) results in an error:
<?php
$fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func(__FUNCTION__, $a++);');
$fn2(1);
// Warning: call_user_func(__lambda_func) [function.call-user-func]: First argument is expected to be a valid callback in T:/test/test.php(21) : runtime-created function on line 1
?>
[EDIT by danbrown AT php DOT net: Combined user-corrected post with previous (incorrect) post.]
You can't refer to a class variable from an anonymous function inside a class method using $this. Anonymous functions don't inherit the method scope. You'll have to do this:
<?php
class AnyClass {
var $classVar = 'some regular expression pattern';
function classMethod() {
$_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' );
$willWork = $_anonymFunc('some string', $classVar);
}
}
?>
The following function is very useful for creating an alias of a user function.
For built-in functions, it is less useful because default values are not available, so function aliases for built-in functions must have all parameters supplied, whether optional or not.
<?php
function create_function_alias($function_name, $alias_name)
{
if(function_exists($alias_name))
return false;
$rf = new ReflectionFunction($function_name);
$fproto = $alias_name.'(';
$fcall = $function_name.'(';
$need_comma = false;
foreach($rf->getParameters() as $param)
{
if($need_comma)
{
$fproto .= ',';
$fcall .= ',';
}
$fproto .= '$'.$param->getName();
$fcall .= '$'.$param->getName();
if($param->isOptional() && $param->isDefaultValueAvailable())
{
$val = $param->getDefaultValue();
if(is_string($val))
$val = "'$val'";
$fproto .= ' = '.$val;
}
$need_comma = true;
}
$fproto .= ')';
$fcall .= ')';
$f = "function $fproto".PHP_EOL;
$f .= '{return '.$fcall.';}';
eval($f);
return true;
}
?>
For who *really* needs the create_function() on php8 (because of legacy code that cannot be changed easily) there is this: "composer require lombax85/create_function".
Best wapper:
<?php
function create_lambda($args, $code) {
static $func;
if (!isset($func[$args][$code])) {
$func[$args][$code] = create_function($args, $code);
}
return $func[$args][$code];
}
In response to kkaiser at revolution-records dot net's note, even tho PHP will allow you to use
<?
$myfunc = create_function('$this', $code);
?>
You can NOT use a reference to "$this" inside of the anonymous function, as PHP will complain that you are using a reference to "$this" in a non-object context.
Currently, I have not found a work-around for this...