2009-04-28 28 views
4

变量中类,我有一些文件test.php的如何包含在PHP

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

和我有一些类

test5.php

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

回答

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

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

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

7

另一种选择是在test2方法中包含test.php。这将使变量的作用域为本地函数。

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

尽管如此,仍然不是一个好的做法。

+1

只要它不被滥用,这是一个非常有用的方法允许类的运行时配置。它还允许您通过拉出函数的“模板”部分并将其放入包含中来将程序逻辑与演示分开。 – 2009-04-28 12:08:29

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; 
    } 
} 
7

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

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"]; 
    } 
} 
?> 
+0

这应该是选择的答案 – lloop 2017-10-04 16:57:35

1

我喜欢做的方式是这样的:

在test.php的

define('CONFIG_KEY_SECURITY', 'test'); 

然后:

在test5.php

include test.php 
    class test1 { 
      function test2 { 
       echo CONFIG_KEY_SECURITY; 
     } 
    } 
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']; 
    } 
}