oop概念中的错误

时间:2014-07-08 15:37:07

标签: php oop

任何正文都可以帮我解决这段代码中的错误(即使它有语法错误);

class SomeClass
{
  protected $_someMember;

  public function __construct() {
    $this->_someMember = 5;
  }

  public static function getSomethingStatic() {
    return $this->_someMember * 10;
  }
}

1 个答案:

答案 0 :(得分:1)

您不能在静态上下文中使用$this,因为您没有实例。

PHP 5.3+代码

<?php

class SomeClass {

  protected $property;

  public function __construct() {
    $this->property = 5;
  }

  protected static function getInstance() {
    return new static();
  }

  public static function getSomethingStatic() {
    return static::getInstance()->property * 10;
  }

}

Pre PHP 5.3 Code

<?php

class SomeClass {

  protected $property;

  public function __construct() {
    $this->property = 5;
  }

  protected static function getInstance() {
    return new SomeClass();
  }

  public static function getSomethingStatic() {
    return self::getInstance()->property * 10;
  }

}