2010-06-02 87 views
0

我試圖在函數中使用已初始化的類,只傳遞給所述函數的類的字符串名稱。僅將類的名稱作爲字符串的訪問類

例子:

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

感謝您的幫助!

回答

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; 
} 
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); 
相關問題