如何更新我的私有布尔属性?

我的“字段”实体:

  /**
  * @ORM\Column(type="boolean",nullable=true)
  */
  private $color;




public function getcolor(): ?bool
  {
    return $this->color;
  }

  public function setColor(?bool $color): self
  {
    $this->color = $color;

    return $this;
  }

我很难更新我的私有财产:

$field = "color"
$content = 1;
$value->{$field} = $content;

我收到错误消息:

  

无法访问私有属性App \ Entity \ Fields :: $ color

所以我对此进行了测试:

$value->setColor(1);

但是我收到错误消息:

  

试图调用一个未定义的名为“ setColor”的方法   类“ stdClass”。

一切正常,只要我将私人改为公开。 但是我只是不知道如何使用私有属性设置值。

nuaadoudou 回答:如何更新我的私有布尔属性?

此代码:

<?php
class MyClass{
    private $attribute;

    public function getAttribute(){
        return $this->attribute;
    }

    public function setAttribute(?int $value){
        if($value)
        $this->attribute = $value;
    }
}

$obj = new MyClass;

//$obj->attribute = 3; //this won't work because attribute is private

$obj->setAttribute(42);

echo $obj->getAttribute();

按预期工作,输出42;尝试创建您班级的新对象,然后执行同样的操作,看看它是否有效。

本文链接:https://www.f2er.com/3165920.html

大家都在问