Reputation: 17643
How do i create my class object in single line from a variable:
$strClassName = 'CMSUsers';
$strModelName = $strClassName.'Model';
$strModelObj = new $strModelName();
The above code successfully creates my CMSUsersModel class object but when i try:
$strClassName = 'CMSUsers';
$strModelObj = new $strClassName.'Model'();
it pops error.... saying:
Parse error: syntax error, unexpected '(' in
Upvotes: 4
Views: 17086
Reputation: 71
As of PHP 8.0.0, using
new
with arbitrary expressions is supported. This allows more complex instantiation if the expression produces a string. (Example #4 Creating an instance using an arbitrary expression)
However, the expression must be wrapped in parentheses. The new
operator is of higher precedence than string concatenation .
(see Operator Precedence), so $strModelObj = new $strClassName.'Model'();
means $strModelObj = (new $strClassName).('Model'());
. The correct parenthesizing would be $strModelObj = new ($strClassName.'Model')();
.
A minimal working example (MWE) for PHP 8:
<?php
class CMSUsersModel {}
$strClassName = 'CMSUsers';
$strModelObj = new ($strClassName.'Model')();
var_dump($strModelObj);
Upvotes: 0
Reputation: 21
I'm note sure because I'm not up to date with classes and PHP, but I think $strModelName
is the class definition, thus I think you have to use one two lines or write something like this:
$strModelName = 'CMSUsers'.'Model'; $strModelObj = new $strModelName();
Upvotes: 1
Reputation: 28755
You can not use string concatenation while creating objects.
if you use
class aa{}
$str = 'a';
$a = new $str.'a'; // Fatal error : class a not found
class aa{}
$str = 'a';
$a = new $str.$str; // Fatal error : class a not found
So You should use
$strModelName = $strClassName.'Model';
$strModelObj = new $strModelName();
Upvotes: 14