从类中的其他文件中定义的访问变量

时间:2011-12-06 15:30:31

标签: php variables scope global-variables global

我想知道是否有办法从PHP中的类访问其他文件中定义的变量。

示例:

file_01.php

<?php
    $a = 42;
?>

file_02.php

<?php
    require_once('file_01.php');

    class mnyClass
    {
        private $myVar;

        function __construct($var = $a)
        {
            $this->myVar = $var;
        }

        function getVar()
        {
            return $this->var;
        }

        function setVar($var)
        {
            $this->myVar = $var;
        }
    }
?>

显然,我的班级更复杂。我选择这个例子是为了更好地理解我尝试做的事情;)

提前谢谢。

4 个答案:

答案 0 :(得分:3)

不能这样做:

    function __construct($var = $a)
    {
        $this->myVar = $var;
    }

你能做的就是通过它:

<?php
    require_once('file_01.php');
    $mnyClass = new mnyClass($a);// the torch has been passed!

    class mnyClass
    {
        private $myVar;

        function __construct($var = null)
        {
            $this->myVar = $var;
        }

        function getVar()
        {
            return $this->var;
        }

        function setVar($var)
        {
            $this->myVar = $var;
        }
    }
?>

你可以这样做(可取):

    function __construct($var = null)
    {
        if($var === null) $var = $GLOBALS['a']; //use global $a variable
        $this->myVar = $var;
    }

答案 1 :(得分:2)

您可以通过GLOBALS访问变量:

http://php.net/manual/en/language.variables.scope.php

编辑:更多细节 -

function __construct() {
  $this->myVar = $GLOBALS['a'];
}

答案 2 :(得分:1)

听起来你正在设置一些应用程序默认值。将这些定义为常量可能是有意义的:

file_01.php:

define('DEFAULT_VALUE_FOR_A', 42);

file_02.php

class myClass
{
    function __construct($var = DEFAULT_VALUE_FOR_A) {
    }
}

答案 3 :(得分:0)

最后,我使用这种方法:

<?php

require_once('file_01.php');

class myClass {

    private $myVar;

    function __construct($var = NULL)
    {
        global $a;

        if($var == NULL)
            $this->myVar = $a;
        else
            $this->myVar = $var; 
    }
}

?>

我在构造函数中将变量$a声明为全局,将my $var的默认值设置为 NULL 并检查是否使用参数调用了构造函数($ var == NULL)。