using 'include' from a class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

using 'include' from a class

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Because of the variable scope
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post 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?
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post 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);
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post 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
Post Reply