简体   繁体   English

在类php中访问外部变量

[英]access outside variable in a class php

Hi i am a newbie to php, 嗨,我是php的新手,

i have a global variable in index.php which has a value. 我在index.php中有一个具有值的全局变量。

index.php: index.php:

global customisedir;
customisedir="2016";

I want to use the value of this variable in a class. 我想在一个类中使用此变量的值。

For ex: 例如:

class RainTPL{

        static $tpl_dir = "tpl/";
        static $custom_dir = "custom/".$customisedir;

***REST OF THE CLASS**

}

But of course it is not working ! 但是,当然不行! can somebody please help. 有人可以帮忙吗?

Thanks 谢谢

All variables in PHP must bear the sign '$'. PHP中的所有变量都必须带有符号“ $”。

Try this code to see if it works: 试试下面的代码,看看它是否有效:

global $customisedir; $customisedir="2016";

I would recommend to include this variable, if possible within the controller class. 如果可能,我建议在控制器类中包括此变量。

you can use a variables from out of class without globalizing it as follow: 您可以使用类外的变量,而无需按以下步骤对其进行全局化:

class RainTPL{
    private $customisedir; private $custom_dir;
    public function __construct($customisedir){  
        $this->custom_dir = "custom/" . $this->customisedir;
    }
    .
    .
    .

so when you call the class it will be: 因此,当您呼叫课程时,它将是:

$RainTPL  = new RainTPL($customisedir);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM