我可以在php中使用USE动态变量的辅助类吗?

时间:2015-05-11 12:18:32

标签: php

我可以使用变量名USE来执行此操作。

use scripts\helpers\$table_use_name;
require_once __DIR__ . DIRECTORY_SEPARATOR . "helpers/$table_use_name";
$table = new $class_name;

1 个答案:

答案 0 :(得分:0)

You can't use use on a dynamic expression, no. However, what you're wanting to do is fairly common. Do it like this:

// Assumes $table_use_name is the name of the class file on disk,
// and $class_name is the name of the PHP class
require_once __DIR__ . DIRECTORY_SEPARATOR . "helpers/{$table_use_name}.php";

$full_class = "scripts\\helpers\\{$class_name}";
$table = new $full_class();

Of course, it is worth putting this in a function, so you don't have to repeat the same logic several times.

Also, you can drop the require_once by implementing an autoloader in your application bootstrap.