Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object from variable name

Tags:

string

php

class

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 
like image 877
KoolKabin Avatar asked Dec 07 '22 22:12

KoolKabin


1 Answers

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();
like image 67
Gaurav Avatar answered Dec 10 '22 13:12

Gaurav