// 項(xiàng)目使用 `composer`
// 重新封裝了 redis
use cache\Redis;
// 因?yàn)榉庋b了幾種緩存方式 如:file,memcache
// 所以想要這種 字符串 的方式來 new 類
// 但是這個(gè)方式直接報(bào)錯(cuò),沒有重名問題
$class = 'Redis';
$instance = new $class($options);
// 如果直接 new,就沒有問題,可以正常運(yùn)行
$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.
Following the voice in heart.
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);
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);