Reputation: 6554
I have a PHP class that makes it just easier to insert templates that 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 is located in a directory outside public_html
as so
kms/php_includes/kms.php
But if I am using it in my index page
public_html/index.php
None of the variables i set in index work inside the templates?
Example
index.php
$user = "Mr.EasyBB";
$controller->template("../kms/site/header");//$controller is the 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 get the undefined variable user
directed to the header php file. Is this due to the origin of the template being outside of public_html
or am I doing something silly here and not realizing it.
Seems to me the problem is the location of the files being in complete different directories so my trivial practice was to add a set and get.
...
private $variables = array();
public function get($prop){
if($this->variables[$prop]){
return $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 as $var->$val){
//i need to assign explicitly the $var name here hence why I used double dollar signs. But it's not working either.
$$var = $val;
}
include $file.".php";
}else{
echo "";
}
}
Upvotes: 0
Views: 150
Reputation: 1163
Those two files cannot communicate with each other because they are given two different scopes; they are included in two separate calls to template()
Try setting $controller->user
within index.php
and reusing it in header.php
.
// controller
function template() {
$this->user = 'Foo';
include 'header.php'; // tells php to use header.php as if
// it were just more code for this function
}
// header.php
echo $this->user; // Foo
You can also stash your variables in an array and extract them before including the header.
// controller
function template() {
$this->templateVars['user'] = 'Foo';
extract($this->templateVars);
echo $user; // Foo
include 'header.php';
}
// header.php
echo $user; // Foo
I would advise against that, however, you can forget where variables come from easily if your templates are large and create their own. But if you need to, you can make the extracted variable names all uppercase to indicate that they came from the controller.
$this->templateVars['USER'] = 'Foo'; // etc
Upvotes: 1