开发者

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->mo开发者_运维百科duleInfo;
}

Thanks for the help!


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜