php - 扩展类和 protected 数据

标签 php

我正在尝试创建一个类来管理小部件。我在父类中遇到 protected 数据的问题:

Widget.php

/** Parent class **/
class Widget{
    protected $html =""; //formated html data
    // method to load views in {system_path}/widgets/{widget_name}/views/
    protected function LoadView($filename){
        if(!empty($filename) && is_string($filename)){
            $output = "";
            $dir = WIDGET_PATH . "views" . DS . $filename;
            ob_start();
                include($dir);
                $output = ob_get_contents();
            ob_end_clean();
            return $output;
        }
        return NULL;
    }

    //method to render formated html data
    public function Render(){
        if(isset($this->html) && !empty($this->html)){
            return $this->html;
        }
        return NULL;
    }
    //static method to load a Widget
    public static function Load($widgetName){
        if(!empty($widgetName) && is_string($widgetName)){
            $widgetName = strtolower($widgetName);
            if(file_exists(WIDGET_PATH . $widgetName . DS . $widgetName . ".php")){
                include_once(WIDGET_PATH . $widgetName . DS . $widgetName . ".php");
                if(class_exists($widgetName."_Widget")){
                    $class = $widgetName."_Widget";
                    return new $class();
                }
            }
        }
        return FALSE;
    }

}

/widgets/socialbar.php

/** SocialBar Widget **/
class Socialbar_Widget extends Widget
{   
    public function __construct(){
        $this->html = "demo"; // test to see if it works
    }
}

索引.php

/*load class files, etc */
$Social = Widget::Load("socialbar"); //works, perfectly loads Socialbar_Widget()

var_dump($social); // works : object(Socialbar_Widget)[29] protected html = 'demo' ......

$Social->Render(); // throws Fatal error: Using $this when not in object context

要在父类中扩展一个变量,我应该使用“public”吗?或者我的错误。 谢谢大家的帮助。

最佳答案

你的类名是类Socialbar_Widget, 你用小写形式调用它

$Social = Widget::Load("socialbar")

并且在加载方法中,您正在执行 strtolower($widgetName)。
检查类文件 name.php。加载函数可能返回 false。

关于php - 扩展类和 protected 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447865/

相关文章:

php - 为什么 PHP 中的 htmlspecialchars_decode 没有对应的 charset 参数?

php - "errorId": "560022", "message": "The X-PAYPAL-APPLICATION-ID header contains an invalid value", "parameter":[ "X-PAYPAL-APPLICATION-ID"]

php/mysql 数组或带有某些值的查询

php - Android App 与 Web 交互

PHP 错误日志已成功发送到 Sentry,但在 Sentry 仪表板上没有显示日志

php - 如何使用 php - mysql 进行 ajax 长轮询

javascript - 如何根据 PHP/Jquery 中选中的复选框数量启用/禁用按钮?

php - 使用 Telegram 的 API 创建群组

php - PDO INSERT 语句错误

php - SQL 结果作为 txt.file 由 php