PHP Magic Methods __set和__get

Jos*_*ega 3 php

这样做会被认为是好的做法......

我有A类,其定义如下:

 class A{
      private $_varOne;
      private $_varTwo;
      private $_varThree;
      public $varOne;


      public function __get($name){

   $fn_name = 'get' . $name;

         if (method_exists($this, $fn_name)){
             return $this->$fn_name();
   }else if(property_exists('DB', $name)){
             return $this->$name;
   }else{
    return null;
   }
      }

  public function __set($name, $value){

   $fn_name = 'set' . $name;

   if(method_exists($this, $fn_name)){
    $this->$fn_name($value);
   }else if(property_exists($this->__get("Classname"), $name)){
    $this->$name = $value;
   }else{
    return null;
   }

  }

      public function get_varOne(){
           return $this->_varOne . "+";
      }


 }

 $A = new A();
 $A->_varOne;     //For some reason I need _varOne to be returned appended with a +

 $A->_varTwo;     //I just need the value of _varTwo
Run Code Online (Sandbox Code Playgroud)

为了不创建4个set和4个get方法,我使用了魔术方法来为我需要的属性调用受尊重的getter,或者只是返回属性的值而不做任何改变.这可以考虑这个好习惯吗?

use*_*291 7

不知道最佳实践,但是当你需要的属性得到它涉及复杂的钙化或DB查询时偷懒装,如__get来是非常有用的.而且,PHP提供一种优雅的方式来缓存通过简单地使用相同的名称,这防止吸气剂被再次调用创建对象字段的响应.

class LazyLoader
{
    public $pub = 123;

    function __get($p) {
        $fn = "get_$p";
        return method_exists($this, $fn) ? 
            $this->$fn() : 
            $this->$p; // simulate an error
    }

    // this will be called every time  
    function get_rand() {
        return rand();
    }

    // this will be called once
    function get_cached() {
        return $this->cached = rand();
    }
}

$a = new LazyLoader;
var_dump($a->pub);       // getter not called
var_dump($a->rand);      // getter called 
var_dump($a->rand);      // once again 
var_dump($a->cached);    // getter called 
var_dump($a->cached);    // getter NOT called, response cached
var_dump($a->notreally); // error!
Run Code Online (Sandbox Code Playgroud)

  • +0 - 虽然我同意上面的内容非常优雅,但只有你不相信使用可见性关键字和前期类声明(我知道你不这样做),这是可行的.对于其他人来说,这就是为什么你不应该为此目的使用魔术方法的一个例子,因为`$ a-> rand`比直接调用`get_rand`慢很多 (2认同)