开发者

Is there a function variable in PHP like in JavaScript?

开发者 https://www.devze.com 2023-02-27 11:09 出处:网络
In JavaScript you can have: var blabla = function(arg){ ... }; Is there something like this in PHP? 开发者_开发百科

In JavaScript you can have:

var blabla = function(arg){
  ...
};

Is there something like this in PHP?

开发者_开发百科

I know about create_function(), but it's really complicated to stuff your code in a string argument.


Since PHP 5.3 you can create anonymous functions like this:

$var = 1;
$func = function( $arg ) use ($var) {
     return $arg + $var;
};

The use clause is required to access variables defined outside the anonymous function.

If you want to change an outside variable in the anonymous function you have to declare it as an reference (by adding an & in front of the $) in the use part:

$var = 1;
$func = function() use ( &$var ) {
   $var = 42;
}
$func();
// $var == 42 now

Otherwise changes made in the anonymous function will not be propagated to the outside.


They are called anonymous functions. In PHP >= 5.3 you can do:

$func = function($a, $b) {
    return $a + $b;
};

$result = $func(3, 4); // returns 7

You can even have closures:

$c = 5;
$func = function($a, $b) use ($c) {
    return ($a + $b) * $c;
};

$result = $func(3, 4); // returns 35

But be aware: the following JavaScript snippet can only be reproduced in PHP using references:

var c = 5;
var f = function(a, b) {
    return (a + b) * c;
};
var r = f(3, 4); // returns 35
c = 6;
r = f(3, 4); // returns 42

In PHP this must look like:

$c = 5;
$func = function($a, $b) use (&$c) {
    return ($a + $b) * $c;
};

$result = $func(3, 4); // returns 35
$c = 6;   
$result = $func(3, 4); // returns 42

Prior to 5.3 you have to use create_function() to create anonymous functions.


Yes, it is available in php 5.3.X

http://php.net/manual/en/functions.anonymous.php

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>


Anonymous functions are available since PHP 5.3.0. link


The syntax is very similar to that of JavaScript; for your particular example, it would be something like the following:

$blabla = function($arg){
  ...
};

The only difference is replacing "var" with "$", and adding a "$" before "arg".

0

精彩评论

暂无评论...
验证码 换一张
取 消