如何在php中包含变量内部类

时间:2009-04-28 11:16:56

标签: php

我有一些文件test.php

<?PHP
    $config_key_security = "test";
?>

我有一些课

test5.php

 include test.php
       class test1 {
                function test2 {
                   echo $config_key_security;
             }
        }

6 个答案:

答案 0 :(得分:18)

   class test1 {
            function test2 {
               global $config_key_security;
               echo $config_key_security;
         }
    }

   class test1 {
            function test2 {
               echo $GLOBALS['config_key_security'];
         }
    }

让你的类依赖于全局变量并不是最佳实践 - 你应该考虑将其传递给构造函数。

答案 1 :(得分:15)

让您的配置文件创建一个配置项数组。然后在类的构造函数中包含该文件,并将其值保存为成员变量。这样,您的所有配置设置都可供该课程使用。

test.php的:

<?
$config["config_key_security"] = "test";
$config["other_config_key"] = true;
...
?>

test5.php:

<?
class test1 {
    private $config;

    function __construct() {
        include("test.php");
        $this->config = $config;
    }

    public function test2{
        echo $this->config["config_key_security"];
    }
}
?>

答案 2 :(得分:7)

另一个选择是在test2方法中包含test.php。这将使变量的范围成为函数的本地。

   class test1 {
            function test2 {
               include('test.php');
               echo $config_key_security;
         }
    }

但仍然不是一个好习惯。

答案 3 :(得分:2)

使用__construct()方法。

include test.php;
$obj = new test1($config_key_security);
$obj->test2();

class test1
{
    function __construct($config_key_security) {
        $this->config_key_security = $config_key_security;
    }

    function test2() {
        echo $this->config_key_security;
    }
}

答案 4 :(得分:2)

我喜欢这样做的方式是:

在test.php中

define('CONFIG_KEY_SECURITY', 'test');

然后:

在test5.php中

include test.php
   class test1 {
            function test2 {
               echo CONFIG_KEY_SECURITY;
         }
    }

答案 5 :(得分:1)

您可以使用$ GLOBALS变量数组并将全局变量作为元素放在其中。

例如: 文件:configs.php

<?PHP
    $GLOBALS['config_key_security'] => "test";
?>

文件:MyClass.php

<?php
require_once 'configs.php';
class MyClass {
  function test() {
    echo $GLOBALS['config_key_security'];
  }
}
相关问题