我正在編程,遇到了這個問題: 在下面的代碼示例中,公共函數設置了一個私有變量。現在人們會認爲私有變量的內容是私有的,認爲$ GLOBALS varriable(超全局)可以訪問它,並且至少讀取它。爲什麼?有沒有一種方法可以做到這一點?爲什麼PHP私有類var不是私有的?
<?PHP
error_reporting(E_ALL);
class test {
private $test = '';
public function test()
{
$this->test = 'Can u see me?';
}
}
$b = new test();
$b->test();
pre($GLOBALS['b']);
// Result:
// test Object
// (
// [test:test:private] => Can u see me?
//)
somefunc();
function somefunc()
{
pre($GLOBALS['b']);
// Result:
// test Object
// (
// [test:test:private] => Can u see me?
//)
}
echo $b->test;
// Result:
// Fatal error: Cannot access private property test::$test
function pre($a) {
echo '<pre>';
print_r($a);
echo '</pre>';
}
?>
謝謝 傑弗裏
您在測試'$ GLOBALS ['b'] - > test'是否會引發致命錯誤嗎?因爲它應該。 – 2012-02-06 22:18:43