访问php类中的外部变量
嗨,我是php的新手 我在访问php类中的外部变量,php,class,global,Php,Class,Global,嗨,我是php的新手 我在index.php中有一个全局变量,它有一个值 index.php: global customisedir; customisedir="2016"; 我想在类中使用这个变量的值 例如: class RainTPL{ static $tpl_dir = "tpl/"; static $custom_dir = "custom/".$customisedir; ***REST OF THE CLASS** } 但它当然不起作用!
index.php
中有一个全局变量,它有一个值
index.php:
global customisedir;
customisedir="2016";
我想在类中使用这个变量的值
例如:
class RainTPL{
static $tpl_dir = "tpl/";
static $custom_dir = "custom/".$customisedir;
***REST OF THE CLASS**
}
但它当然不起作用!有人能帮忙吗
谢谢PHP中的所有变量都必须带有符号“$” 请尝试以下代码以查看其是否有效:
global $customisedir; $customisedir="2016";
如果可能的话,我建议将此变量包括在控制器类中。您可以使用类外变量,而无需将其全局化,如下所示:
class RainTPL{
private $customisedir; private $custom_dir;
public function __construct($customisedir){
$this->custom_dir = "custom/" . $this->customisedir;
}
.
.
.
因此,当您调用该类时,它将是:
$RainTPL = new RainTPL($customisedir);
使用公共$customisedir=“2016”代码>或在变量初始化之前使用
$