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

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

WBOY
Release: 2016-06-06 20:13:22
Original
1107 people have browsed it

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

提示未找到

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

Class 'ArticleSearch' not found</code>
Copy after login
Copy after login

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

回复内容:

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

提示未找到

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

Class 'ArticleSearch' not found</code>
Copy after login
Copy after login

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

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

请试试这么写

OR

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template