Dominic
Dominic

Reputation: 1

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

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:

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!

Upvotes: 0

Views: 43

Answers (2)

Jarrod Nettles
Jarrod Nettles

Reputation: 6283

Pass the object itself into the function as the parameter.

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

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;
}

$art = new Art;

getModuleInfo($art);

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

var $moduleInfo makes $moduleInfo an (php4 style, public) instance property, i.e. each instance of the class art has it's own (separate) member $moduleInfo. Therefore the name of the class won't do you much good. You have to specify/pass the instance you want to refer to.
Maybe you're looking for static properties, see http://docs.php.net/language.oop5.static

class art {
  static public $moduleInfo = "Hello World";  
}

getModuleInfo("art");

function getModuleInfo($moduleName){
  echo $moduleName::$moduleInfo;
}

Upvotes: 1

Related Questions