微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

魔术方法__set和__get的双重行为,带有property_exists函数,并且没有它

如何解决魔术方法__set和__get的双重行为,带有property_exists函数,并且没有它

我正在尝试在类中以及在测试__set()和__get()方法时理解Magic函数代码

class kids{
 
 private $height;
 public function __set($property, $value){
//if(property_exists($this, $property))
      $this->property= $value; //this works
}

 public function __get($property){
 return "The child's height is " . $this->$property . " inches tall";
  }

}
$kid1= new kids;

$kid1->height= 45;

echo $kid1->height;

输出

The child's height is 45 inches tall

我的问题:

输出正确,但是如果我取消注释if(property_exists($this, $property)),则__set被调用两次,并且除非我像这样写$this->$property= $value;,否则不会更改height的值,除非将$this->property加到$ The child's height is inches tall

具有property_exists()的输出


@Entity(tableName = "notes")
public class Note implements Parcelable {
    public static final String ID = "id";
    @Ignore
    public final String TAG = getClass().getName();
    @PrimaryKey(autoGenerate = true)
    public long id;
    @ColumnInfo(name = "header")
    private String header = "";
    @ColumnInfo(name = "body")
    private String body = "";
    @ColumnInfo(name = "date")
    private String date = "";
    
    public Note() {}

    public Note(String body){
        this.body=body;
        setDate();
    }
    public Note(String header,String body) {
        this.header = header;
        this.body = body;
        setDate();
    }
    public Note(String header,String body,String date){
        this(header,body);
        setDate(date);
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setDate() {
        Date currentTime = Calendar.getInstance().getTime();
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-mm-dd hh:mm");
        date = sm.format(currentTime);
    }

    public String getDate() {
        return date;
    }

    public boolean isEmpty() {
        return header.isEmpty() && body.isEmpty();
    }

    @Override
    public String toString() {
        return "Note{" +
                " \"header\":" + header +
                ",\n\"body\":" + body + "\n" +
                "}";
    }

    @Override
    public boolean equals(Object other) {
        Note o = (Note) other;
        return id == o.id;
    }

    public boolean equalsIgnoreDate(Note other) {
        if (other == null)
            return false;
        return header.equals(other.getHeader()) && body.equals(other.getBody());
    }
}

我尝试谷歌搜索问题,但发现是property_exists()函数无法检测使用__get magic方法可以魔术访问的属性。我不明白这个笔记。 如果有人可以阐明这一点,将不胜感激。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。