好的,这是解决的实际问题:
使用命名空间:
\home\Homecontroller::get(); // returns what I want
不使用命名空间:
$str = "Homecontroller@get"
$caller = explode('@', $str);
$caller[0]::$caller[1](); // returns what I want
每次尝试动态失败都会失败
\$namespace\$caller[0]::$caller[1](); // fails
eval("\\${namespace}\\${caller[0]}::${caller[1]}()"); // fails
我在homecontroller.php文件中的:
<?php
namespace home;
class Homecontroller {
public function Homecontroller()
{
throw new Exception("Homecontroller is a static class");
}
public static function jsonify($data)
{
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 2016 05:00:00 GMT');
header('Content-type: application/json');
print json_encode ($data);
exit();
}
public static function get()
{
$data = [];
$data['message'] = "You have called the GET function";
self::jsonify($data);
}
}
我正在构建一个需要尊重命名空间的框架,但没有特别注意它们。我需要保留外部配置文件中列出的命名空间。
答案 0 :(得分:1)
将完全限定的类名构建为字符串,然后在其上调用方法:
namespace home;
class Homecontroller {
private function __construct()
{}
public static function jsonify($data)
{
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 2016 05:00:00 GMT');
header('Content-type: application/json');
print json_encode ($data);
exit();
}
public static function get()
{
$data = [];
$data['message'] = "You have called the GET function";
self::jsonify($data);
}
}
$namespace = "home";
$str = "Homecontroller@get";
$caller = explode('@', $str);
$cls = "\\$namespace\\$caller[0]";
$method = $caller[1];
$cls::$method();
//or use call_user_func
call_user_func([$cls, $method]);