PHP about the use of new
typecho
typecho 2017-06-29 10:08:15
0
3
811
// 项目使用 `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.

typecho
typecho

Following the voice in heart.

reply all(3)
世界只因有你

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);
三叔

It has been solved, thank you.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template