I have created a Page class and all the pages on my website are objects of that Page class. Each Page object has a title attribute which is passed in as an argument to the constructor and so creating a new Page object looks as follows.
<?php
require_once('library/Page.php');
$page = new Page('About');
$page->header();
开发者_JAVA百科This is where the problem arises.
The header() method is...
public function header()
{
require_once($this->templatePath . 'header.php');
}
I then echo the page title using
<?php echo $page->title; ?>
However, I get the following error.
Notice: Undefined variable: page in /Users/aaronfalloon/Projects/PHP/tfm/template/header.php on line 19 Notice: Trying to get property of non-object in /Users/aaronfalloon/Projects/PHP/tfm/template/header.php on line 19
Let me further explain about what Gumbo has written.
When you included the template file, you did the operation WITHIN the header function, thus making all $page variable in the template file referring to the local $page variable in the header function, which apparently is not declared/defined.
You should use $this->title instead to refer to the current class.
It is something like
class Page{
public function header(){
echo $this->title;
}
}
when you try to include the template file:
// page class
class Page{
public function header(){
include('template.php');
}
}
.
// template file
echo $this->title;
Use $this->title
instead of $page->title
since you refer to the property of the very same instance.
I'm not sure, it may be possible to solve this issue by adding global $page;
before the require_once
call in your Page::header
function.
The require_once includes the code of the specified file and execute it keeping the current scope. In your Page::header
function, $page
is not visible.
$page
is declared as a global and the header.php code has only local scope to the method.
Either:
Use global $page
after the method declaration before the require_once
.
Pass $page
into the header function as an argument public function header($page)
.
Use echo $this->title
in header.php.
Or if you really want to screw around use extract(get_object_vars($this))
and echo $title
.
精彩评论