douyun1546 2013-01-21 21:50
浏览 127
已采纳

扩展类和受保护的数据

im trying to create a class to manage widgets. I have problems with a protected data in parent class:

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

index.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

To extend a variable inside parent class should i use "public"? Or what i mistake. Thanks for help guys.

  • 写回答

1条回答 默认 最新

  • dtqpw68806 2013-01-22 23:26
    关注

    Your class name is class Socialbar_Widget, Your are calling it in lower case

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

    and in load method you are doing strtolower($widgetName).
    Check class file name.php. Load function may have returning false.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比