Passing variables to an included file
I have a template class which goes like this:
class Template{
public $pageTitle = "";
public function __construct($pageTitle){
$this->pageTitle = $pageTitle;
}
public function display(){
include "/includes/head.php";
include "/includes/body.php";
}
}
Now, I'm used to Java's workings but I don't understand why I'm 开发者_如何学运维getting an undefined variable ($pageTitle) error. The included files need to be able to access that variable. I know it's going to be very simple but I actually haven't found out why. What do I need to do to allow includes to see this variable?
The includes will also have to use $this->pageTitle
. Effectively, the include
makes them part of the method body.
The included file lives in the same scope as your object. So you need to call:
$this->pageTitle
If you don't want to do the whole $this->, you can do something like the following... The extract function will extract the array $this->data into variables with names respective to the key/index of each item. So now you will be able to do echo $pageTitle;
class Template{
public $data = Array();
public function __construct($pageTitle){
$this->data['pageTitle'] = $pageTitle;
}
public function display(){
extract($this->data);
include "/includes/head.php";
include "/includes/body.php";
}
}
Scope is a little different in PHP than in java. For your specific case you need
$this->pageTitle
To access a variable declared outside the class, you'll need to make it global
global $myVar;
精彩评论