Reputation: 2733
main.controller.php:
final class MainController extends Controller {
public function is_locked() {
$lock = new View('lock');
Res::render($lock);
}
}
view.class.php:
final class View {
private $data;
public function get_title() {
return isset($this->title) ? $this->title : DEFAULT_TITLE;
}
public function get_layout() {
return isset($this->layout) ? $this->layout : 'base';
}
public function get_layout_path() {
return SITE_PATH .'app/views/layouts/'. $this->get_layout() .'.layout.php';
}
public function get_path() {
return SITE_PATH .'app/views/' .$this->name .'.view.php';
}
public function print_title() {
echo $this->get_title;
}
public function __construct($name) {
$this->data = array();
$this->data['name'] = $name;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error('Undefined property via __get(): '. $name .' in '. $trace[0]['file'] .' on line' . $trace[0]['line'], E_USER_NOTICE);
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
here is my render method on my response class:
public static function render($view) {
include_once SITE_PATH .'app/views/layouts/root.layout.php');
}
called from one of my controllers... the param $view is a simple View object...
Here is my root.layout.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?php $view->print_title(); ?></title>
</head>
<body>
root layout
</body>
</html>
It seems i can't access to the $view object from the layout file included, may be a silly question, but right now i really can't realize why should not work...
Could someone explain me how php work in that situation? What I'm doing wrong?
Upvotes: 0
Views: 57
Reputation: 41060
Use include
instead of include_once
, since your method can be called several times and it would work only the first ("once") time.
The PHP documentation says about the scope of include (and also include_once):
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Therefor everything should work with your passed $view
variable.
There is also a nice example (the first one on the page) which explains that any variable available in the line before including will be available in the included file.
Upvotes: 1