Reputation: 1152
is their a way to create an array that stores both strings and functions that generate strings?
<?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";
}
will output:
calling foo()
calling bar()
is there some way to implement the array so that I get the output:
calling foo()
bar
something like
$data[] = &foo;
$data[] = "bar";
foreach ($data as $element) {
if (is_callable($element) && !is_string($element)) return $element();
else return $element;
}
Upvotes: 0
Views: 56
Reputation: 78994
I'm not sure why you would need this, but the problem is that the way you are doing it they are always strings and if they are callable there is no way to differentiate. How about using the key or something similar, since the array is ordered by the order of creation:
$data["foo"] = "foo";
$data[] = "bar";
foreach ($data as $key => $element) {
if (is_callable($element) && is_string($key)) {
echo $element()."\n";
} else {
echo $element."\n";
}
}
Another possibility (there are many):
$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";
}
}
If you store code you could eval:
$data[] = "echo foo();";
$data[] = "echo 'bar';";
foreach ($data as $element) {
eval($element);
}
Upvotes: 1