php区分函数和字符串
它们是创建存储字符串和生成字符串的函数的数组的一种方法吗php区分函数和字符串,php,function-pointers,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)) e
<?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()
bar
差不多
$data[] = &foo;
$data[] = "bar";
foreach ($data as $element) {
if (is_callable($element) && !is_string($element)) return $element();
else return $element;
}
我不知道你为什么需要这个,但问题是你这样做的方式,它们总是字符串,如果它们是可调用的,就没有办法区分。既然数组是按创建顺序排序的,那么使用键或类似的东西怎么样
$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[] = "echo foo();";
$data[] = "echo 'bar';";
foreach ($data as $element) {
eval($element);
}
您可以在数组中存储闭包,而不是神奇地拥有其他任务的字符串。您可以使用实现
\uu toString()
-method的对象。您放弃了吗?我最终做了与第二个选项非常相似的事情。
$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);
}