I have classname stored in variable $classname; also I have an array of values I should pass into object constructor.
$classname = "MyClass";
$variables = array(1, 2, 3, 4);
I need
$objInstance = new MyClass(1, 2, 3, 4);
How?
Thank you.
Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
You can use Class. forName() to get a Class object of the desired class. Then use getConstructor() to find the desired Constructor object. Finally, call newInstance() on that object to get your new instance.
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
Simply speaking, a constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object.
$r = new ReflectionClass($classname);
$objInstance = $r->newInstanceArgs($variables);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With