doujiang2020 2013-09-19 16:28
浏览 59
已采纳

使用__call或__get&__set进行动态设置和获取?

I don't like having hundreds of naive Setters and Getters but I like to be able to have Setters and Getters for some of the data, since I might have to sanitize them etc.

I've got two ideas how to do this:

class Test {
  private $value = "Value received from: ";
  private $value2 = "Value2 received from: ";

  function __get($property) {
    if (method_exists($this, "get".$property)) {
      return $this->getValue();
    }

    return $this->$property."__get()";
  }

  public function getValue() {
    return $this->value."getValue()";
  }
}

$obj = new Test();
echo $obj->value; // Returns: Value received from: getValue()
echo $obj->value2; // Returns: Value2 received from: __get()

And

class Test {
  private $value = "Value received from: ";
  private $value2 = "Value2 received from: ";

  public function __call($method, $args) {
    if (substr($method, 0, 3) == "get") {
      // Sanitizing so no functions should get through
      $property = preg_replace("/[^0-9a-zA-Z]/", "", strtolower(substr($method, 3)));

      if (isset($this->$property)) {
        return $this->$property."__call";
      }
    }
  }

  public function getValue() {
    return $this->value."getValue()";
  }
}

$obj = new Test();
echo $obj->getValue(); // Returns: Value received from: getValue()
echo $obj->getValue2(); // Returns: Value2 received from: __call

Basically the only difference is between magic method __call and __get. I left out __set because it's pretty obvious how I would do it.

The real question is which one is better? Performance? Readability? Security?

  • 写回答

2条回答 默认 最新

  • duanfengwang9157 2013-09-19 17:53
    关注

    According to the PHP Manual: Overloading, the magic method __get() is for overloading properties, while __call() is for methods. Since you are working with methods, you should use the one appropriate for its designed use. So for Readability, __call() gets my vote.

    As far as Security, I think any overloading is just about as equally secure, which is to say not really much at all, since it's about creating properties and methods that haven't been explicitly declared.

    I haven't tested the Performance aspect of it. I would think the method __call() would be better as it was designed for use with methods, but you may want to microtime(true) a couple tests to see if it matters.

    I honestly don't use __call() since I haven't had the need to overload methods in my apps, or otherwise should say that I always declare methods in my object classes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器