View Single Post
Old 11-11-2007, 12:56 AM   #4 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Since the view file (views/home.php) is included within the class method (display) then all variables within that view file will be in the scope (PHP Manual page) of that class method.

To make it work you have a few options. Your first option is to define $var as global in your view (or the display method) with global $var (which is a nasty way of handling the situation). Secondly, you could replace $var with $GLOBALS['var'] in your view file (I don't like this way). A third way would be to pass along the 'template variables' into the display method and extract them to be used in your view. I like this last way.

PHP Code:
// class
    
public function display($szView$aVars = array())
    {
        if (
file_exists('views/' $szView '.php'))
        {
            
// See http://php.net/extract for usage
            
extract($aVarsEXTR_SKIP EXTR_REFS);
            include(
'views/' $szView '.php');
        }
    }

// index
include('function/function.php');
$aTplVars        = array();
$aTplVars['var'] = 1;  // $var in view file
$aTplVars['foo'] = 'bar'// $foo in view file
display('home'$aTplVars); 
There are lots more possibilities, but lets see if you're comfortable with the above first.
Salathe is offline  
Reply With Quote