Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new class instance from function return value - one-liner

Tags:

php

class

Does there exist a one-liner (yes, I love them) to create new instance of a class based on the returned string of a function?

$obj = new {functionThatReturnsAStringValue()}();
like image 227
silkfire Avatar asked Feb 18 '23 00:02

silkfire


2 Answers

I understand what you want, but i think you can do it that way:

$obj = ($class = functionThatReturnsAStringValue()) ? new $class() : null;
like image 108
Barif Avatar answered Feb 19 '23 13:02

Barif


function getObject()
{
  return 'DateTime';
}

$datetime = call_user_func(function ($obj) { return new $obj; }, getObject());
like image 26
MichaelRushton Avatar answered Feb 19 '23 14:02

MichaelRushton