如何在php中包含类内变量

如何在php中包含类内变量,php,Php,我有一些test.php文件 <?PHP $config_key_security = "test"; ?> 或 让您的类依赖全局变量不是真正的最佳实践——应该考虑将其传递给构造函数。另一个选项是在Test2方法中包含Test.PHP。这将使变量的作用域成为函数的局部 class test1 { function test2 { include('test.php'); echo $c

我有一些test.php文件

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


让您的类依赖全局变量不是真正的最佳实践——应该考虑将其传递给构造函数。

另一个选项是在Test2方法中包含Test.PHP。这将使变量的作用域成为函数的局部

   class test1 {
            function test2 {
               include('test.php');
               echo $config_key_security;
         }
    }
但是仍然不是一个好的实践。

使用_construct()方法


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

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

我更喜欢这样做:

在test.php中

define('CONFIG_KEY_SECURITY', 'test');
然后:

在test5.php中

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

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

例如: 文件:configs.php

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

文件:MyClass.php


只要不被滥用,这是允许类的运行时配置的非常有用的方法。它还允许您通过拉出函数的“模板”部分并将其放入include来将程序逻辑与表示分离。这应该是选择的答案
test5。php
是最好的方法
<?
class test1 {
    private $config;

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

    public function test2{
        echo $this->config["config_key_security"];
    }
}
?>
define('CONFIG_KEY_SECURITY', 'test');
include test.php
   class test1 {
            function test2 {
               echo CONFIG_KEY_SECURITY;
         }
    }
<?PHP
    $GLOBALS['config_key_security'] => "test";
?>
<?php
require_once 'configs.php';
class MyClass {
  function test() {
    echo $GLOBALS['config_key_security'];
  }
}