Home >Backend Development >PHP Tutorial >Yii2 为何无法通过变量来创建对象呢?

Yii2 为何无法通过变量来创建对象呢?

WBOY
WBOYOriginal
2016-06-06 20:13:221123browse

<code>use root\modules\article\models\ArticleSearch;
$model='ArticleSearch';
$searchModel=new $model();</code>

提示未找到

<code>PHP Fatal Error – yii\base\ErrorException

Class 'ArticleSearch' not found</code>

是使用了命名空间的原因吗?

回复内容:

<code>use root\modules\article\models\ArticleSearch;
$model='ArticleSearch';
$searchModel=new $model();</code>

提示未找到

<code>PHP Fatal Error – yii\base\ErrorException

Class 'ArticleSearch' not found</code>

是使用了命名空间的原因吗?

<code>$model='root\modules\article\models\ArticleSearch';
$searchModel=new $model();</code>

请试试这么写

OR

<code>use root\modules\article\models\ArticleSearch;
$model= ArticleSearch::className();
$searchModel=new $model();
</code>

通过变量创建类的时候,一定要包含类全名,不能通过命名空间替代。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn