4

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 
KoolKabin
  • 17,157
  • 35
  • 107
  • 145

3 Answers3

14

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();
Gaurav
  • 28,447
  • 8
  • 50
  • 80
1

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();
htoip
  • 437
  • 5
  • 19
Jochen G.
  • 21
  • 1
0

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);
Steve4585
  • 36
  • 4