为什么需要文件但变量仍未定义

Why file is required however variable is still undefined

我试图理解 PHP 中的 OOP 方式。而且我认为 - 不确定这种情况 - 我对变量范围有疑问。这是我的问题

  1. 在运行之后test.php;为什么我无法访问 $nums 变量 foo.php
  2. 解决方法是什么?
  3. 如果解决方案需要在某处使用 global 关键字,什么是 我的另一个选项没有 global 关键字。 (我不想用)

foo.php

<?php
$nums = array(4, 7);
$s = $nums[0]+$nums[1];
echo 'string in foo.php is written here.<br> SUM is '.$s.'<br>';
print_r($nums);
echo '<br><br>';

test.php

<?php

class Loader {

    private static $load_name;

    public static function loadFile($load_file) {

        self::$load_name = $load_file;

        $file_to_load = self::$load_name;

        require_once($file_to_load);

        unset($file_to_load);
    }
}

class TestClass {

    public function getnums() 
    {
        $a = Loader::loadFile("foo.php");

        echo 'var_dump($a) :<br><pre>'; var_dump($a); echo '</pre>'; 

        echo 'var_dump($nums) :<br><pre>'; var_dump($nums);     echo '</pre>';
    }
}

$n = new TestClass();
$g = $n->getnums();

echo 'var_dump($g) :<br><pre>'; var_dump($g); echo '</pre>';

test.php returns

string in foo.php is written here.
SUM is 11
Array ( [0] => 4 [1] => 7 ) 

var_dump($a) :
NULL

var_dump($nums) :


Notice:  Undefined variable: nums in ...UniServerZ\www\test.php on line 27

NULL

var_dump($g) :
NULL

您 100% 正确 - 问题出在示波器上。

$nums只会在文件范围和包含范围内定义;在这种情况下,这就是 Loader::loadFile() 函数。

如果您想从文件中检索变量并使其在您的 getnums() 方法中可用,您将需要一种方法使其从 loadFile 返回。我相信您假设变量 $a.

会自动发生这种情况

要完成这项工作,请尝试:

public static function loadFile($filename) {
  // ... existing code
  return $nums;
}

然后 $a 将是 $nums.

为了使它更详细和可重用:

function loadFile($filename, $variableName) {
  // existing code here.
  return $$variableName; // variable variables are a dangerous thing to debug.
}

因此您的 getnums() 函数将如下所示:

$a = Loader::loadFile("foo.php", "nums"); // "nums" being the variable name.