我想知道是否有办法用命名空间调用变量函数。基本上我正在尝试解析标签并将它们发送到模板函数,以便它们可以呈现html`
这是一个例子:(我使用的是PHP 5.3)
// Main php file
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
echo template\$tag();
}
// template.php
namespace template;
function javascript() { return "Hello from javascript"; }
function css() { return "Hello from css"; }
function script() { return "Hello from script"; }
我一直在
解析错误:语法错误,意外的T_VARIABLE,期望在第76行的T_STRING ...
谢谢!马特
当然可以,但不幸的是,你需要使用 call_user_func()
为了达成这个:
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
echo call_user_func('template\\'.$tag);
}
PHP中的命名空间相当新。我相信将来他们会修复它,所以我们不会要求 call_user_func()
了。
这也行,不需要 call_user_func
,只需使用 可变功能文件 特征:
require_once 'template.php';
$ns = 'template';
foreach (array('javascript', 'script', 'css') as $tag) {
$ns_func = $ns . '\\' . $tag;
echo $ns_func();
}
试试吧
// Main php file
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
call_user_func("template\\$tag"); // As of PHP 5.3.0
}
// template.php
namespace template;
function javascript() { return "Hello from javascript"; }
function css() { return "Hello from css"; }
function script() { return "Hello from script"; }
你有一些信息 这里
尝试这个
$p = 'login';
namespace App\login;
$test2 = '\App\\'.$p.'\\MyClass';
$test = new $test2;