Geting object with class name as String

Hi!

I’m trying to get an object with class name as String.

The simple way is
$object=DataObject\MyClass::getById(25);

can I do the same thing using a string containing my class name?
$className=“MyClass”;

Thanks in advance,

Yes, i PHP you can use variables in classnames.

It would look like this:

$className = "MyClass"
// get an existing DataObject
$object = DataObject\$className::getById(25);

// create a new DataObject
$object = new DataObject\$className();

But if you have the ID of the object you want to get, you can use the AbstractObject (the base class of all objects) to get it:

$id = 25;
$object = DataObject\AbstractObject::getById($id);

(Use this only if you’re sure the given id is an object of your desired class!)

Hi, Thank you for your answer,
I tryed to add your solution in my code

image

However it gives the folowing error:

### (1/1) FatalThrowableError
Parse error: syntax error, unexpected '$classeName' (T_VARIABLE), expecting identifier (T_STRING)

Thanks again,

Oh sorry, I forgot.

You have to create a string variable with the whole class name, like this:

$className = "MyClass";
$fullClassName = "Pimcore\Model\DataObject\" . $className;

$object = $fullClassName::getById(25);
// or
$object = new $fullClassName();
1 Like

Thank you so much! it works
Thanks again for your help!