【问题标题】:How to use variables from php file where require/include is declared如何使用声明了require/include的php文件中的变量
【发布时间】:2017-12-18 18:34:42
【问题描述】:

所以基本上,我有一个用于连接 mysql 数据库的 config.php 文件,以及一个包含一些函数的 functions.php 文件。在我的所有文件(例如索引、登录、注册)中,我使用require('config.php'); 行和在config.php 中我有require('functions.php'); 这一行用于在我的索引中使用require('config.php'); 行包含配置+ 函数,登录和 register.php 文件。

所以基本上我的问题是,我在 config.php 中声明的变量在 functions.php 中无法识别。如何让它发挥作用?

提前致谢。

【问题讨论】:

标签: php mysql


【解决方案1】:

您可以使用global variavlename$GLOBAL['variavlename without $']

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a;
    $a = $a + $GLOBALS['b'];
} 

Sum();
echo $a;
?>

【讨论】:

    【解决方案2】:

    很可能您的函数不起作用,因为它们的scope does not include the variables you are trying to use

    首先,确保functions.php被包含在变量设置之后

    另外,让你的函数Public Functions,或者,通过这样做在函数中声明全局变量:

    $testVariable = "test";
    function testFunction() {
         global $testVariable;
    }
    

    【讨论】:

    • @Sadman 如果我的回答对您有所帮助,请确保您检查我的回答旁边的那个小检查按钮以将其标记为正确。请并谢谢你:)
    【解决方案3】:

    使用 global 语句将函数内部的变量声明为全局变量。

    function myfunction() {
      global $myvar;  // $myvar set elsewhere can be read within this function
                      // and if its value changes in this function, it changes globally
    }
    

    【讨论】:

    • public 关键字仅用于类结构。
    • 非常感谢!
    猜你喜欢
    • 2012-01-18
    • 2011-10-30
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 2011-05-05
    • 2012-09-29
    相关资源
    最近更新 更多