访问类 PHP 中的外部变量


access outside variable in a class php

嗨,我是php的新手,

index.php有一个全局变量,它有一个值。

索引.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);