【问题标题】:PHP classses/functionsPHP 类/函数
【发布时间】:2011-05-15 13:50:33
【问题描述】:

如何将 $str 变量(如下)放入我的班级?该函数用于动态调用每个类,而不是有“很多” 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 到类。

请有任何建议。谢谢

【问题讨论】:

    标签: php class-design instance-variables subclass


    【解决方案1】:

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

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

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

    【讨论】:

    • 嗨 lonesomeday - 谢谢。奇怪,我最初是这样写的,但它不起作用一定是错过了什么。但现在可以了,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    相关资源
    最近更新 更多