簡體   English   中英

我可以通過php中的USE動態變量使用幫助程序類嗎?

[英]Can I use a helper class by USE dynamic variable in php?

我可以使用USE(通過變量名)嗎?

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

您不能在動態表達式上使用use ,否。 但是,您想要做的事情很普遍。 像這樣做:

// 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();

當然,將其放在一個函數中是值得的,因此您不必重復相同的邏輯幾次。

另外,您可以通過在應用程序引導程序中實現自動加載器來刪除require_once

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM