问题 PHP中具有命名空间的变量函数


我想知道是否有办法用命名空间调用变量函数。基本上我正在尝试解析标签并将它们发送到模板函数,以便它们可以呈现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 ...

谢谢!马特


9096
2017-08-09 01:04


起源

好问题...... - Alix Axel
你正在使用 可变功能 错了,它需要是变量,而不是字符串和变量。 - hakre


答案:


当然可以,但不幸的是,你需要使用 call_user_func() 为了达成这个:

require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
    echo call_user_func('template\\'.$tag);
}

PHP中的命名空间相当新。我相信将来他们会修复它,所以我们不会要求 call_user_func() 了。


5
2017-08-09 01:14



需要一个参数。这是如何做到这一点。 echo call_user_func('template \\'。$ tag,$ params); - Matt


这也行,不需要 call_user_func,只需使用 可变功能文件 特征:

require_once 'template.php';

$ns = 'template';
foreach (array('javascript', 'script', 'css') as $tag) {
    $ns_func = $ns . '\\' . $tag;
    echo $ns_func();
}

7
2017-08-09 16:52



这也更快。请参阅php docs。 - Rudie


试试吧

 // 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"; }

你有一些信息 这里


1
2017-08-09 01:14



::?真的......有人要么不做功课,要么根本不了解命名空间和类的静态成员之间的区别。 - Andrew Moore
谢谢!虽然稍微偏了!我很感激帮助。 - Matt
@Andrew你是对的。当粘贴代码时,我搞砸了。谢谢 - Gabriel Sosa


尝试这个

$p = 'login';
namespace App\login; 
$test2 = '\App\\'.$p.'\\MyClass';

$test = new $test2;

0
2018-03-12 20:07