Access class with only the name of the class as a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sigepmest37
Forum Newbie
Posts: 2
Joined: Wed Jun 02, 2010 12:25 pm

Access class with only the name of the class as a string

Post by sigepmest37 »

I am attempting to use an already initialized class in a function with only the string name of the class being passed to said function.

Example:

Code: Select all

class art{
  var $moduleInfo = "Hello World";
}

$art = new Art;

getModuleInfo("art");

function getModuleInfo($moduleName){
    //I know I need something to happen right here.  I don't want to reinitialize the class since it has already been done.  I would just like to make it accessible within this function.
    
    echo $moduleName->moduleInfo;
}
Thanks for the help!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Access class with only the name of the class as a string

Post by requinix »

While possible - and only sometimes - it's a bad idea. Why does it need to be done this way?
sigepmest37
Forum Newbie
Posts: 2
Joined: Wed Jun 02, 2010 12:25 pm

Re: Access class with only the name of the class as a string

Post by sigepmest37 »

tasairis wrote:While possible - and only sometimes - it's a bad idea. Why does it need to be done this way?
I have an array that holds all the "modules" and their parameters. I loop through this array building different pages and widgets etc. The array supplies the names of the classes and function that need to be used.

The function "getModuleInfo" is called a bunch of times throughout the course of a page build to build each individual widget on that specific page. There may be 5 widgets that use 5 different classes on one page, and this is dictated by the "modules array" I mentioned earlier.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Access class with only the name of the class as a string

Post by requinix »

Then pass the variables themselves, not just their names.

Code: Select all

$art = new Art;

getModuleInfo($art);
Post Reply