【问题标题】:When to use $this->$property何时使用 $this->$property
【发布时间】:2015-05-30 22:19:36
【问题描述】:

我无法理解何时以及为什么需要使用 $this->$property。因此,将$ 添加到this 关键字和property。我只在__get()__set() 的魔术方法中看到了这个。有人可以详细说明吗?

【问题讨论】:

  • 也许当属性名称保存在一个变量中(例如$var = "ThisIsMyProperty";)然后你像这样使用它:$this->$var?!

标签: php class oop methods


【解决方案1】:

$property 包含属性名称时,您可以使用$this->$property;当$function 包含函数名称时,您可以使用$this->$function()

例子:

class MyClass {
    private $email = "rr@rr.com";

    public function getProperty($p){
        return $this->$p;
    }
}

$obj = new MyClass;
$obj->getProperty("email"); // Returns rr@rr.com

【讨论】:

  • 同意@Richard Reiber
  • 啊,我明白了。那么引用属性/方法?谢谢先生。
  • @JuanRangel:是的。没问题。你也可以看到the documentation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多