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
  • 16,247
  • 35
  • 104
  • 145

2 Answers2

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
  • 27,714
  • 8
  • 48
  • 78
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
  • 427
  • 5
  • 19
Jochen G.
  • 21
  • 1