初始化函数以php中的Variable形式

问题描述 投票:-4回答:2

如何在php中将函数设置为变量类似于list函数

example: list($x,$y)=array(1,2); // this is okey ,but...

我如何创建这样的结构?

php function variables
2个回答
1
投票

您正在谈论变量函数,如果变量名称附加了括号,PHP将查找与变量求值的名称相同的函数,并尝试执行它。除此之外,这可以用于实现回调,函数表等。

这是来自PHP手册Variable Functions的小例子

function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()

另一种情况是Anonymous functions,也称为闭包,允许创建没有指定名称的函数。它们作为回调参数的值非常有用,但它们还有许多其他用途。

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

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

0
投票
<?php
$my_array = array("Dog","Cat","Horse");

list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>

list()函数用于将值分配给变量列表。像array()一样,这不是一个函数,而是一个语言结构。 list()用于在一个操作中分配变量列表。

© www.soinside.com 2019 - 2024. All rights reserved.