Monday 15 February 2010

php - Class include not letting variables work inside templates -



php - Class include not letting variables work inside templates -

i have php class makes easier insert templates i've created...

ie

... /*get templates*/ public function template($file){ if(isset($file) && file_exists($file.".php")){ $controller = $this; include $file.".php"; }else{ echo ""; } }

which located in directory outside public_html so

kms/php_includes/kms.php

but if using in index page

public_html/index.php

none of variables set in index work within templates?

example

index.php

$user = "mr.easybb"; $controller->template("../kms/site/header");//$controller class variable

header.php

echo $user; //this doesn't work $controller->template("../kms/site/svg/smile"); //this still works

but in kms/site/header.php

i undefined variable user directed header php file. due origin of template beingness outside of public_html or doing silly here , not realizing it.

seems me problem location of files beingness in finish different directories trivial practice add together set , get.

... private $variables = array(); public function get($prop){ if($this->variables[$prop]){ homecoming $this->variables[$prop]; } } public function set($prop=null,$val=null){ if($prop !== null && $val !== null){ $this->variables[$prop] = $val; } } /*get templates*/ public function template($file){ if(isset($file) && file_exists($file.".php")){ $controller = $this; foreach($this->variables $var->$val){ //i need assign explicitly $var name here hence why used double dollar signs. it's not working either. $$var = $val; } include $file.".php"; }else{ echo ""; } }

those 2 files cannot communicate each other because given 2 different scopes; included in 2 separate calls template()

try setting $controller->user within index.php , reusing in header.php.

// controller function template() { $this->user = 'foo'; include 'header.php'; // tells php utilize header.php if // more code function } // header.php echo $this->user; // foo

you can stash variables in array , extract them before including header.

// controller function template() { $this->templatevars['user'] = 'foo'; extract($this->templatevars); echo $user; // foo include 'header.php'; } // header.php echo $user; // foo

i advise against that, however, can forget variables come if templates big , create own. if need to, can create extracted variable names uppercase indicate came controller.

$this->templatevars['user'] = 'foo'; // etc

php class include undefined

No comments:

Post a Comment