php 学习系列: 变量的作用域
1<?php
2class SystemComponent{
3 var $settings;
4
5 function getSettings()
6 {
7 $settings['dbhost'] = 'localhost';
8 // more
9 return $settings;
10 }
11}
12?>
2class SystemComponent{
3 var $settings;
4
5 function getSettings()
6 {
7 $settings['dbhost'] = 'localhost';
8 // more
9 return $settings;
10 }
11}
12?>
这个代码有没有问题?
我认为 line 3 和 line 7 的 $settings 变量是不一样的,也就是说 line 3 这行代码有和没有一个样。为了验证这一点,写测试代码如下:
<?php
class SystemComponent{
var $settings;
function SystemComponent() {
$this->settings['dbhost'] = 'hello';
}
function getSettings()
{
$settings['dbhost'] = 'localhost';
// more
return $settings;
}
}
$settings = SystemComponent::getSettings();
print $settings['dbhost'] . '<br/>';
$sc = new SystemComponent();
$set = $sc->getSettings();
print $set['dbhost'] . '<br/>';
print $sc->settings['dbhost'] . '<br/>';
?>
class SystemComponent{
var $settings;
function SystemComponent() {
$this->settings['dbhost'] = 'hello';
}
function getSettings()
{
$settings['dbhost'] = 'localhost';
// more
return $settings;
}
}
$settings = SystemComponent::getSettings();
print $settings['dbhost'] . '<br/>';
$sc = new SystemComponent();
$set = $sc->getSettings();
print $set['dbhost'] . '<br/>';
print $sc->settings['dbhost'] . '<br/>';
?>
输出的结果是:
localhost
localhost
hello
localhost
hello
基本证明了我的想法。