1php 学习系列: 变量的作用域<?php
 2php 学习系列: 变量的作用域class SystemComponent{
 3php 学习系列: 变量的作用域    var $settings;
 4php 学习系列: 变量的作用域
 5php 学习系列: 变量的作用域    function getSettings()
 6php 学习系列: 变量的作用域    {        
 7php 学习系列: 变量的作用域        $settings['dbhost'= 'localhost';
 8php 学习系列: 变量的作用域        // morephp 学习系列: 变量的作用域
 9php 学习系列: 变量的作用域        return $settings;
10php 学习系列: 变量的作用域    }
11php 学习系列: 变量的作用域}
12php 学习系列: 变量的作用域?>

这个代码有没有问题?
我认为 line 3 和 line 7 的 $settings 变量是不一样的,也就是说 line 3 这行代码有和没有一个样。为了验证这一点,写测试代码如下:

php 学习系列: 变量的作用域<?php
php 学习系列: 变量的作用域
class SystemComponent{
php 学习系列: 变量的作用域    
var $settings;
php 学习系列: 变量的作用域    
php 学习系列: 变量的作用域    
function SystemComponent() {
php 学习系列: 变量的作用域        
$this->settings['dbhost'= 'hello';        
php 学习系列: 变量的作用域    }
php 学习系列: 变量的作用域    
php 学习系列: 变量的作用域    
function getSettings()
php 学习系列: 变量的作用域    {        
php 学习系列: 变量的作用域        
$settings['dbhost'= 'localhost';
php 学习系列: 变量的作用域        
// morephp 学习系列: 变量的作用域
php 学习系列: 变量的作用域
        return $settings;
php 学习系列: 变量的作用域    }
php 学习系列: 变量的作用域}
php 学习系列: 变量的作用域
php 学习系列: 变量的作用域
$settings = SystemComponent::getSettings();
php 学习系列: 变量的作用域
print $settings['dbhost'. '<br/>';
php 学习系列: 变量的作用域
php 学习系列: 变量的作用域
$sc = new SystemComponent();
php 学习系列: 变量的作用域
$set = $sc->getSettings();
php 学习系列: 变量的作用域
print $set['dbhost'. '<br/>';
php 学习系列: 变量的作用域
print $sc->settings['dbhost'. '<br/>';
php 学习系列: 变量的作用域
?>

输出的结果是:
localhost
localhost
hello

基本证明了我的想法。

相关文章:

  • 2021-12-10
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-10
  • 2022-12-23
  • 2021-12-24
  • 2021-11-08
  • 2022-01-18
  • 2021-12-04
相关资源
相似解决方案