魔术方法__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 (将#修改为@)