Page 1 of 1

using 'include' from a class

Posted: Thu May 10, 2007 3:45 pm
by GeXus

Code: Select all

class TemplateControl{
	
	function display(){
		
		$page = basename($_SERVER['SCRIPT_FILENAME']);
		$page = str_replace('.php','', $page);
		
		$template = $page . '_template.php';
		return include('templates/'.$template);
		
	}

}

$template = new TemplateControl();
$a = '1';
$template->display();
I have the above class... that is basically going to be used as a simple wrapper for including php files that I will use as "templates"... If I include the template page directly it will pass the $a variable, however by using the class... it does not. Any idea why that would be?

Posted: Thu May 10, 2007 3:48 pm
by volka
Because of the variable scope

Posted: Thu May 10, 2007 3:53 pm
by GeXus
Would that mean that $a would need to be global if i'm including within the class? Or could somehow the include be global?

Posted: Thu May 10, 2007 3:58 pm
by Begby
Maybe something like this to avoid using globals (using global is like being a communist sympathizer).

Code: Select all

class TemplateControl{
       
        function display( $vars ){
               
                $page = basename($_SERVER['SCRIPT_FILENAME']);
                $page = str_replace('.php','', $page);
               
                extract($vars) ; // look this up on php.net to see what it does

                $template = $page . '_template.php';
                return include('templates/'.$template);
               
        }

}

$template = new TemplateControl();
$vars['a'] = '1';
$template->display($vars);

Posted: Thu May 10, 2007 4:28 pm
by GeXus
Ah nice.. hmm.. I wonder if this is the best way to do it... any suggestions for what I'm trying to accomplish? I'd rather use native php, then use a template system.. but I would still like to try and break apart most of the design logic