// 项目使用 `composer`
// 重新封装了 redis
use cache\Redis;
// 因为封装了几种缓存方式 如:file,memcache
// 所以想要这种 字符串 的方式来 new 类
// 但是这个方式直接报错,没有重名问题
$class = 'Redis';
$instance = new $class($options);
// 如果直接 new,就没有问题,可以正常运行
$instance = new Redis($options);
The first error is like this PHP Fatal error: Class 'Redis' not found
.
If I don’t use namespace automatic loading and use include file
, the first and second options are no problem.
What is the principle of this and how to solve it? Thank you.
世界只因有你2017-06-29 10:10:15
When using a namespace and instantiating a variable as a class name, needs to include the complete namespace
, and add the namespace directly where instantiated
$cls_name = 'Redis';
$class = "\cache\Redis\".$cls_name;
$instance = new $class($options);
高洛峰2017-06-29 10:10:15
Requires full namespace
use cache\Redis;
$class = Redis::class;//需要完整的命名空间
$instance = new $class($options);
OR
$class = '\cache\Redis';
//$class = \cache\Redis::class;
$instance = new $class($options);