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 
3
  • Why do need this 'optimization'? Commented Apr 1, 2011 at 9:32
  • You cannot do string concatenation while object instantiation. Commented Apr 1, 2011 at 9:55
  • possible duplicate of Instantiate new object from variable Commented Jul 9, 2015 at 18:38

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.