【问题标题】:PHP include file into custom "namespace"PHP将文件包含到自定义“命名空间”中
【发布时间】:2013-05-22 06:45:15
【问题描述】:

我需要/包含一个文件,以将来自外国软件的配置值提取到我正在开发的软件中。

是否可以通过 include/require 以某种方式处理外部 php 文件,并将其中的所有变量加载到数组中,或者至少将其设置为自定义命名空间以防止它重置现有变量?

外部应用程序相当老旧,使用普通的 PHP 和变量赋值来为运行做准备。

例子:

$db_type = 'mysql';
$db_user = 'hello';
$db_pass = 'world';
$charset = 'UTF-8'; 

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以将此代码包含在函数中。所有这些变量都将在本地范围内。

    function get_old_data() {
        include 'old.php';
    
        // do whatever you want with these variables
    
    }
    

    【讨论】:

    • 太好了,谢谢!只是完全忘记了函数有自己的本地范围。
    【解决方案2】:

    我假设您知道要从外部配置中使用的配置变量的名称。

    您可以创建一个函数,在其中包含文件,从变量构建一个数组,然后您可以返回给调用者。

    在这种情况下,外部文件将在函数的本地范围内执行,并且不应覆盖外部变量。

    function loadconfig() {
      include 'external.php';
      // do calculations and build var_array
      return $var_array;
    }
    

    【讨论】:

      【解决方案3】:

      您可以在包含的文件中使用 return。

      可以在包含的文件中执行 return 语句,以终止该文件中的处理并返回到调用它的脚本。

      Include.

      例子:

      // config.php
      return array('db_type' => 'mysql',
          'db_user' => 'hello',
          'db_pass' => 'world',
          'charset' => 'UTF-8',);
      

      那就这样用吧

      $config = include 'config.php';
      

      即使这样

      $connection = new Connection(include 'config.php');
      

      【讨论】:

      • 感谢您的想法 - 我已经知道这种方式,但正如我所说,它是一个现有的外部应用程序,我无法修改文件,这终止了在配置文件中简单地返回数组的能力.
      猜你喜欢
      • 2014-04-26
      • 1970-01-01
      • 2010-11-15
      • 2011-05-29
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2013-03-04
      相关资源
      最近更新 更多