Extensible class and protected data

im trying to create a class to manage widgets. I have problems with secured 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 a parent class, should I use "public"? Or that I am wrong. Thanks for the help guys.

+3


source to share


1 answer


Your class name is Socialbar_Widget class, you call it in lower case

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

      



and in download mode you execute strtolower ($ widgetName).
Check your class file name.php. The load function can return false.

+1


source







All Articles