【问题标题】:Variables set in a file required within a function still cause a "Notice: Undefined variable" warning在函数中所需的文件中设置的变量仍会导致“注意:未定义变量”警告
【发布时间】:2017-01-08 08:51:13
【问题描述】:

我希望能够包含或需要来自同一父目录(模块)的文件,只需键入我想要包含的文件的名称,而无需总是写出require_once('../app/modules/user/user.php'),所以我想出了包装它的想法全部在这样的函数中:

index.php 文件。

//index.php

        function require_file($modules=array())
                {
                    foreach($modules as $module) {
                        if (is_dir('../app/modules/' . $module) && file_exists('../app/modules/' . $module . '/' . $module . '.php')) {
                            require_once('../app/modules/' . $module . '/' . $module . '.php');
                        } else {
                            die('The module <strong>' . $module . '</strong> does not exist in the modules directory');
                        }
                    }
                }

    // and then require my files like this:

        $modules = array();

        $modules[] = 'user';

        require_file($modules);

这是我的目录的样子:

1. app
   - modules
     - user
       - user.php
2. public
   - index.php

这是我的 user.php 文件:

//user.php

$user = 'My Name';

问题来了;

  1. 如果在 index.php 中使用 user.php 文件中设置的变量,仍然会抛出 注意:未定义变量:user 而不会导致 @987654326 失败@test,当它失败时,它会输出一条消息,说“模块 user 模块不存在于模块目录中”,就像它应该的那样。

  2. 当我在函数之后需要文件时,检查之前是否需要文件一次,如下所示:

index.php

    function require_file($modules=array())
            {
                foreach($modules as $module) {
                    if (is_dir('../app/modules/' . $module) && file_exists('../app/modules/' . $module . '/' . $module . '.php')) {
                        require_once('../app/modules/' . $module . '/' . $module . '.php');
                    } else {
                        die('The module <strong>' . $module . '</strong> does not exist in the modules directory');
                    }
                }
            }

// and then require my files like this:

    $modules = array();

    $modules[] = 'user';

    require_file($modules);

    require_once('../app/modules/user/user.php');

它不起作用,因为显然它之前已经被要求过一次。

问题是......我做错了什么?

【问题讨论】:

  • 所以,除了user.php,您向我们展示了所有内容。你希望我们猜到那里有什么?
  • 它就在那里...带有一个设置变量 $user。
  • 您可能想了解PHP Autoloading,它几乎完全符合您的要求(在类的上下文中)

标签: php


【解决方案1】:

变量$user 定义在require_file 函数范围内。这是通知的原因。

您需要在user.php 文件中将$user 声明为全局 变量:

//user.php
global $user;
$user = 'My Name';

虽然这不是一个好主意。您应该将模块创建为类。如果您忘记此模块中的变量 $user 并在另一个模块中声明另一个 $user 变量,则会干​​扰。

【讨论】:

  • 该项目不是面向对象的……我还在学习 php。你能告诉我怎么做吗?
  • 答案已编辑。如果你不需要加载类,自动加载器就没有用了。
  • @GermanLashevich 这些文件可以很容易地编辑成类,从长远来看,这将是最好的。 OP 正在学习 PHP 现在是学习 OOP 的最佳时机,而不是学习过程之后...它避免了诸如global 之类的坏习惯
  • @Martin 你是对的。但有两个方面:解决当前任务和学习最佳实践。当前问题的上下文不够清楚,无法显示如何准确地重写代码以使用类。
  • 在探索了执行此操作的选项之后,没有太多,我认为值得的一切都是对最佳实践的某种破坏。闭包可能是一种方法,但会在函数中添加各种新变量,并且 file_get_contents 需要使用 eval 等。
猜你喜欢
  • 1970-01-01
  • 2017-12-17
相关资源
最近更新 更多