簡體   English   中英

PHP 吸氣劑/設置器

[英]PHP getters / setters

我正在嘗試學習這個 MVC OOP 東西,我偶然發現了一個奇怪的錯誤:

Fatal error: Call to undefined method Foo::stuff() in ...

我的代碼:

class Foo extends FooBase{

  static $_instance;
  private $_stuff;

  public function getStuff($which = false){
    if($which) return self::app()->_stuff[$which]; else return self::app()->_stuff;
  }

  public function setStuff($stuff){
    self::app()->_stuff = $stuff;
  }

  public static function app(){
    if (!(self::$_instance instanceof self)){
      self::$_instance = new self();
    }

    return self::$_instance;
  }

}

Foo::app()->stuff = array('name' => 'Foo', 'content' => 'whatever');

echo Foo::app()->stuff('name'); // <- this doesn't work...

FooBase class 看起來像這樣:

class FooBase{

  public function __get($name){
    $getter = "get{$name}";
    if(method_exists($this, $getter)) return $this->$getter();
    throw new Exception("Property {$name} is not defined.");
  }

  public function __set($name, $value){
    $setter = "set{$name}";
    if(method_exists($this, $setter)) return $this->$setter($value);
    if(method_exists($this, "get{$name}"))
      throw new Exception("Property {$name} is read only.");
    else
      throw new Exception("Property {$name} is not defined.");

  }
}

所以如果我理解正確,吸氣劑 function 不能有 arguments? 為什么? 還是我在這里做錯了什么?

任何帶有省略號的東西都被視為一種方法。 神奇的__get__set方法只適用於看起來像屬性的東西。

有關方法魔術,請參閱__call()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM