php中的静态引用不符合预期

时间:2014-07-15 14:35:14

标签: php static hhvm

我遇到了一个奇怪的问题 下面粘贴的代码适用于HHVM(版本3.1.0),但它在PHP(版本5.5.9)中失败,并显示一条非常奇怪的错误消息。

<?php

namespace DummyTest\Lib {
  class TObject {
    public function __construct() {
    }
  }
  class TComponent extends \DummyTest\Lib\TObject {
    public function __construct() {
      parent::__construct();
    }
  }
  class TSingletonComponent extends \DummyTest\Lib\TComponent {
    public function __construct() {
      parent::__construct();
    }
  }
  class TDatabase extends \DummyTest\Lib\TSingletonComponent {
    public function __construct() {
      parent::__construct();
    }
    public static function Init() {
      $db = new \DummyTest\Lib\Database\TPDO();
    }
  }
}

namespace DummyTest\Lib\Database {
  class TDatabase extends \DummyTest\Lib\TComponent {
    public function __construct() {
      parent::__construct();
    }
  }
  class TPDO extends \DummyTest\Lib\Database\TDatabase {
    protected $pdo;
    public function __construct() {
      parent::__construct();
      echo \DummyTest\SystemConfig::Get('xxx'); // <-- This fails in PHP
    }
  }
}

namespace DummyTest {
  class SystemConfig {
    protected static $config = array();
    public function Get($name) {
      echo get_called_class().PHP_EOL;
      if(isset(static::$config[$name])) {
        return static::$config[$name];
      }
      return null;
    }
    public function Set($name, $value) {
      static::$config[$name] = $value;
    }
  }

  SystemConfig::Set('xxx', 'yyy');
  \DummyTest\Lib\TDatabase::Init();
}

当我在HHVM中运行此代码时,它正确地响应了&#39; yyy&#39; 但在PHP中,我收到以下错误消息:&#34; PHP致命错误:访问未声明的静态属性:DummyTest \ Lib \ Database \ TPDO :: $ config in /home/.../bugtest/staticclass.php on line 50&#34;

我不明白为什么会失败。类\ DummyTest \ SystemConfig不会从任何类继承,类\ DummyTest \ Lib \ Database \ TPDO不会从\ DummyTest \ SystemConfig继承。那为什么PHP会失败呢? 如果我将\ DummyTest \ SystemConfig中的static :: $ config [$ name]更改为self :: $ config [$ name],它将在PHP和HHVM中按预期工作。

此代码是从较大的项目中提取的。但是提取的代码与较大的项目的行为相同
有关当前环境的更多信息是它是运行Ubuntu 14.04的计算机,代码是从命令行执行的。

1 个答案:

答案 0 :(得分:1)

Get()应该是静态的

public static function Get($name)
相关问题