访问类,只将类的名称作为字符串

时间:2010-06-02 18:23:23

标签: php oop

我试图在一个函数中使用一个已初始化的类,只将该类的字符串名称传递给所述函数。

示例:

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

var $moduleInfo使$ moduleInfo成为一个(php4样式,公共)实例属性,即类art的每个实例都有自己的(单独的)成员$ moduleInfo。因此,班级的名称对你没有多大好处。您必须指定/传递要引用的实例 也许您正在寻找静态属性,请参阅http://docs.php.net/language.oop5.static

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

getModuleInfo("art");

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

答案 1 :(得分:0)

将对象本身作为参数传递给函数。

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