Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
I am building an application right now and I am throwing up a quick-and-dirty framework for it because I just don't have the time to do much more. I have a simple function for capturing a file's html into a variable to use for my view:
function capture_file($file){
ob_start();
include $file;
return ob_get_clean();
}
The problem is that variables declared in the $file are inside of this function and therefor have its scope. What can I do to acheive this same functionality, but not have to send capture_file all of the variable that $file needs... ?
class Template_Php {
var $file = '';
var $tags = array();
function set($tag, $value) {
$this->tags[$tag] = $value;
}
function render(){
ob_start();
extract($this->tags);
include $this->file;
return ob_get_clean();
}
}
good call... this is the only part of the framework where I wasn't using OOP... I will just convert what I've already done to use a view object. Thanks buddy.
class Template
{
public function __construct() { }
public function __set($name, $value)
{
if (isset($this->$name)) {
//spit error about variable existing already
}
$this->$name = $val;
}
public function capture_file($file)
{
ob_start();
include $file;
return ob_get_clean();
}
}
$template = new Template();
$template->title = 'Home';
You can take advantage of the __set method in this case, or just use another method to register variables to the class to give your template file the variable scope. There are so many different ways, just play around for a bit.
can't use __set cuz it's php4. (which is really why I am just kind of throwing it together... I have a sneaking suspicion I will have to rebuild it anyway so I can merge it with a php5 project... man I love this stuff!!
class View{
var $_vars = array();
function set($name, $value){
$this->_vars[$name] = $value;
}
function render($file){
//TODO: check that $file is really a file
ob_start();
extract($this->_vars);
include $file;
return ob_get_clean();
}
}