Jump to content

Using method return to name an object


zombi

Recommended Posts

Ok as you can see, I'm creating an object and using $controller_request to name it. In the below code $controller_request is used to store the string returned from the $application->get_controller() method. Is there a way I can condense the two lines so that I no longer require $controller_request?

 


$controller_request = $application->get_controller();

$controller = new $controller_request($application->get_action());

Link to comment
https://forums.phpfreaks.com/topic/127089-using-method-return-to-name-an-object/
Share on other sites

I've heard of discussions like this, and to me it doesn't make sense. It doesn't seem possible. Have you tried to do it?

 

This is what you want to do, right?

 

$controller = new $application->get_controller()($application->get_action());

 

Er, no that wouldn't work.

 

Again, does it matter?

Optimising code doesn't always end up working out for the greatest. If you are worried about an extra line then why do you use two variables? Surely you could use something like this:

$controller = $application->get_controller();
$controller = new $controller($application->get_action());

 

Or why don't you make it so that the constructor function in the class accepts an argument?

$controller = $application->get_controller($application->get_action());

 

Something like that maybe?

I think you're getting the words "object" and "class name" confused.  You don't create an instance using an object, you create an instance using a class.  If $controller_request is an object, it makes no sense to do this:

 

$controller = new $controller_request($application->get_action());
/* Doesn't make sense if $controller_request is an object. */

 

Now, if you meant to say that $controller_request contains a class name and you want to instantiate that class, you can't do it like that.  You can't normally ask PHP to do that.  $controller_request is a variable.  PHP doesn't go into your variables and runs the code inside them.

 

The exception is the eval() function.  This function allows you to construct a string and explicitly tell PHP to run that string as though it were code.  You should avoid using it too often though because you take a big performance hit from it.

 

eval("$controller = new ".$application->get_controller()."($application->get_action());");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.