PHP类/函数

时间:2010-11-25 08:42:17

标签: php class-design instance-variables subclass

如何将$ str变量(下面)放入我的类/类中?该函数用于动态调用每个类,而tan有“很多”if(class_exists)语句。

页面上的

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;    

} }

我无法实现的是将“str”从函数调用通过函数“拉”到类中。

请提出任何建议。感谢

1 个答案:

答案 0 :(得分:2)

我认为您正试图从类$str访问变量widget;如果不是这样,请纠正我。

您需要将变量作为参数传递给构造函数:

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