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

mon*_*oys 4 php

我有一些文件test.php

<?PHP
    $config_key_security = "test";
?>
Run Code Online (Sandbox Code Playgroud)

我有一些课

test5.php

 include test.php
       class test1 {
                function test2 {
                   echo $config_key_security;
             }
        }
Run Code Online (Sandbox Code Playgroud)

Gre*_*reg 19

   class test1 {
            function test2 {
               global $config_key_security;
               echo $config_key_security;
         }
    }
Run Code Online (Sandbox Code Playgroud)

要么

   class test1 {
            function test2 {
               echo $GLOBALS['config_key_security'];
         }
    }
Run Code Online (Sandbox Code Playgroud)

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


JW.*_*JW. 15

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

test.php的:

<?
$config["config_key_security"] = "test";
$config["other_config_key"] = true;
...
?>
Run Code Online (Sandbox Code Playgroud)

test5.php:

<?
class test1 {
    private $config;

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

    public function test2{
        echo $this->config["config_key_security"];
    }
}
?>
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 7

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

   class test1 {
            function test2 {
               include('test.php');
               echo $config_key_security;
         }
    }
Run Code Online (Sandbox Code Playgroud)

尽管如此仍然不是一个好习惯.

  • 只要不被滥用,这是一种允许类运行时配置的非常有用的方法。它还允许您通过拉出函数的“模板”部分并将其放入包含中来将程序逻辑与表示分离。 (2认同)

Sta*_*ish 5

使用 __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;
    }
}
Run Code Online (Sandbox Code Playgroud)