我尝试在PHP中理解OOP方式。而且我认为 - 对于这种情况不确定 - 我有可变范围的问题。这是我的问题:
test.php
后;为什么我无法访问$nums
变量
foo.php
? 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返回
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
答案 0 :(得分:0)
你是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.