0

I'm looking for a way to create a new object with the help of a variable, but instead of referencing it by the variable I want to reference it by the value of the variable.

$name = "moduleAjax";
$name = new $name;

And instead of doing this,

$name->method();

I would do this,

$moduleAjax->method();

I don't have a live example of my code. I've been experimenting a little bit but I can't find a solution.

Any help would be greatly appreciated.

2
  • This seems rather strange. Do you mind explaining what situation you would need this in? Commented Apr 20, 2013 at 20:01
  • Creating modules for a project. Modules are loaded from folders to minimize the amount of code people have to write in order to make them work and then they can use $moduleName->moduleMethod(); Commented Apr 20, 2013 at 20:09

1 Answer 1

3

You search for variable variables: http://php.net/manual/en/language.variables.variable.php

So write:

$name = "moduleAjax";
$$name = new $name; // a dollar sign was added to $name

Then you can access this newly created instance of the class named moduleAjax with the variable $moduleAjax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.