php告诉函数和字符串

时间:2018-06-06 19:50:39

标签: php function-pointers

是一种创建数组的方法,该数组存储生成字符串的字符串和函数吗?

<?php

function foo()
{
    return "calling foo()";
}


function bar()
{
    return "callin bar()";
}


$data = array();
$data[] = "foo";
$data[] = "bar";

foreach ($data as $element) {
    if (is_callable($element)) echo $element()."\n";
    else echo $element."\n";
}

将输出:

calling foo()
calling bar()

有没有办法实现数组,以便我得到输出:

calling foo()
bar

类似

$data[] = &foo;
$data[] = "bar";

foreach ($data as $element) {
    if (is_callable($element) && !is_string($element)) return $element();
    else return $element;
}

1 个答案:

答案 0 :(得分:1)

我不确定你为什么需要这个,但问题是你做它的方式总是字符串,如果它们是可调用的,就没有办法区分。如何使用键或类似的东西,因为数组按创建顺序排序:

$data["foo"] = "foo";
$data[] = "bar";

foreach ($data as $key => $element) {
    if (is_callable($element) && is_string($key)) {
        echo $element()."\n";
    } else {
        echo $element."\n";
    }
}

另一种可能性(有很多):

$data[]['fnc'] = "foo";
$data[]['str'] = "bar";

foreach ($data as $element) {
    if (isset($element['fnc']) && is_callable($element['fnc'])) {
        $element = $element['fnc'];
        echo $element()."\n";
    } else {
        echo $element['str']."\n";
    }
}

如果你存储代码,你可以评估:

$data[] = "echo foo();";
$data[] = "echo 'bar';";

foreach ($data as $element) {
    eval($element);
}