Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new object using classname stored in variable and how to pass another variable into this class's constructor?

Tags:

php

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.

like image 246
Kirzilla Avatar asked Mar 09 '10 23:03

Kirzilla


People also ask

How do you create a variable object in Java?

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.

How do you create an object using class forName in Java?

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.

Can you create an instance of a class using its constructor?

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.

Can we create object for constructor?

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.


1 Answers

$r = new ReflectionClass($classname);
$objInstance = $r->newInstanceArgs($variables);
like image 166
user187291 Avatar answered Oct 25 '22 22:10

user187291