【问题标题】:how to access a php variable inside a function from an included file如何从包含的文件访问函数内的 php 变量
【发布时间】:2014-02-14 19:36:58
【问题描述】:

我有一个名为 test1.php 的文件,其中包含许多变量和一些函数定义。我正在尝试将此文件包含到另一个名为 test2.php 的文件中,并使用变量和函数。

test1.php

$i = "a";
$ii = "b";
$iii = "c";
function test1a(){ return "lol";  }

test2.php

function test2a(){ include 'test1.php'; return $i; }
function test2b() { include 'test1.php'; return test2c(); }
function test2c(){ include 'test1.php'; return $iii; }
function test2d() { include 'test1.php'; return test1a(); }

index.php

include 'test2.php'
echo test2a(); 
echo test2b(); 
echo test2c();
echo test2d();

原因:

我在两台不同的服务器上拥有相同的代码库。只有 test2.php 文件会有所不同。每个服务器在 test2.php 中会有不同的值,但具有相同的变量名。 test2.php 有点像本地化文件。

我的问题是一些变量或没有显示出来。有一个更好的方法吗。我不想在每个函数中都包含该文件。

谢谢。

【问题讨论】:

    标签: php variables include global


    【解决方案1】:

    您正试图多次包含一个函数的文件。函数总是全局的。所以第二个包含给你一个致命错误Fatal error: Cannot redeclare test1a() (previously declared in [..])

    你应该把这个函数放在单独的文件中并使用include_once。

    【讨论】:

      【解决方案2】:

      反过来做:

      将所有不同的变量放入一个文件中的一个数组中,没有任何函数:

      //config.php
      $config['setting1'] = "val1";
      $config['setting2'] = "val2";
      $config['setting3'] = 42;
      ...
      

      还有:

      //index.php
      include_once("config.php");
      echo $config['setting1'];
      ....
      

      现在您可能在不同的服务器上有不同的配置,而无需更改任何功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 2014-04-08
        • 2017-05-07
        • 2011-02-20
        • 2022-01-09
        • 2021-12-30
        • 2011-05-20
        相关资源
        最近更新 更多