I've made a test database from the book "PHP and mySQL Novice to Ninja"... now I'm testing out making the structure better by using templates to output the html. This is the template... note the part in asterixes. That's the dynamic content which should change based upon what page is passed to it.
<!DOCTYPE html>
<html lang="en">
<head>
<link href= "/project/includes/style.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<title>Joke Database Project</title>
</head>
<body>
<div id="topheader">
<p>Joke Database Project</p>
</div>
<div id="navigation">
<?php include $_SERVER['DOCUMENT_ROOT'] .'/project/includes/navbar.html.php'; ?>
</div>
<div id="container">
**<?php include '/'.$content;?>**
</div>
</body>
</html>
It works fine when I use the following code in my php script:
$content="authors.html.php";
include $_SERVER['DOCUMENT_ROOT'] . '/project/includes/html_template.html.php';
However I want to make it less clunky so I decided to create the following function in my helpers.inc.php file which is included in the main php script:
function showpage($content)
{
include $_SERVER['DOCUMENT_ROOT'] . '/project/includes/html_template.html.php';
}
So I just want to use showpage("author.html.php") to show that content in the template. The problem I'm having is when I use this function it no longer recognises the variables from the main script.
How can I get around this in an elegant way?
for your problem about scope : when u want call a variable from out of function u should use this code :
var $myvar ;
function myfunct () {
$GLOBALS['myvar']
}
You are including the template in the scope of the function thus the variables outside are not accessible. You can create a class that will hold the showpage() function and assign the variables to it using the magic methods __set and __get:
class Controller {
private $data = array();
public function __set($name, $value)
{
$this->data[$name] = $value;
}
public function __get($name)
{
if (array_key_exists($name, $this->data))
{
return $this->data[$name];
}
//else handle errors
}
public function showpage($path)
{
include $_SERVER['DOCUMENT_ROOT'] . '/project/includes/' . $path;
}
}
$ctrl = new Controller();
$ctrl->var1 = $var1;
$ctrl->var2 = $var2;
$ctrl->showpage("path/to/page");
Then you can use $this->varName in the template.
You should probably read about MVC in php.