2010-11-25 46 views
1

如何獲取$ str變量(下面)到我的類/類中?該函數用於動態調用每個類,而不是使用if(class_exists)語句的「大量」。PHP類別/函數

頁:

echo rh_widget('Search'); 

功能(在功能頁):

function rh_widget($str) { 
global $db, $table_prefix; 
$newwidget = 'rh_'.strtolower($str); 
    if(class_exists($newwidget)): 
    $rh_wid = new $newwidget(); 
    echo $rh_wid->rh_widget; 
    endif; 

}

然後父&子類(類頁),例如:

class widget { 
public $str; 
function __construct() { 
$this->before_widget .= '<ul class="rh_widget">'; 
$this->before_title .= '<li><h3>'.$str.''; 
$this->after_title .= '</h3><ul>'; 
$this->after_widget .= '</ul></li></ul>'; 
} 

}

class rh_search extends widget { 
public function __construct() { 
parent::__construct(); 
global $db, $table_prefix; 
    $this->rh_widget .= $this->before_widget; 
    $this->rh_widget .= $this->before_title.' '.$this->after_title; 
    $this->rh_widget .= '<li>Content etc. in here</li>'; 
    $this->rh_widget .= $this->after_widget;  

}}

我不能讓發生是從函數調用功能,通過「拉」 $海峽通過的類。

請任何建議。謝謝

回答

2

我認爲你正試圖訪問變量$strwidget類;如果情況並非如此,請糾正我。

您需要將變量作爲參數傳遞給構造函數:

class widget { 
    public $str; 
    function __construct($str) { // add $str as an argument to the constructor 
     $this->before_widget .= '<ul class="rh_widget">'; 
     $this->before_title .= '<li><h3>'.$str.''; 
     $this->after_title .= '</h3><ul>'; 
     $this->after_widget .= '</ul></li></ul>'; 
    } 
} 

class rh_search extends widget { 
    public function __construct($str) { // add $str to the constructor 
     parent::__construct($str); // pass $str to the parent 
     global $db, $table_prefix; 
     $this->rh_widget .= $this->before_widget; 
     $this->rh_widget .= $this->before_title.' '.$this->after_title; 
     $this->rh_widget .= '<li>Content etc. in here</li>'; 
     $this->rh_widget .= $this->after_widget;  
    } 
} 

function rh_widget($str) { 
    global $db, $table_prefix; 
    $newwidget = 'rh_'.strtolower($str); 
    if(class_exists($newwidget)): 
     $rh_wid = new $newwidget($str); // pass $str to the constructor 
     echo $rh_wid->rh_widget; 
    endif; 
} 
+0

lonesomeday嗨 - 感謝您的。奇怪的是我最初是這樣寫的,但沒有奏效,一定錯過了一些東西。但現在有用,謝謝 – rmap 2010-11-25 09:01:41