簡體   English   中英

如何從對象數組中刪除私有屬性?

[英]How can I remove a private property from an array of object?

$array = $this->em->getRepository($entity)->filter($id);

有了學說,我正在創建一個數組:

array:24 [▼
  0 => Members^ {#543 ▼
    -id: 1
    -username: "lio"
    -email: "info@somepage.com"
    -isActive: true
    -name: "Lio"
    -projects: PersistentCollection^ {#590 ▶}
    -pages: PersistentCollection^ {#615 ▶}
  }
  1 => Members^ {#135029 ▶}
  2 => Members^ {#125937 ▶}
  3 => Members^ {#1807 ▶}
  4 => Members^ {#135075 ▶}
  5 => Members^ {#135086 ▶}

從這個數組中,我嘗試刪除對象項目:

 foreach ($array as $value) {
      dump($value->projects);
    }

我收到該對象是私有的錯誤消息。

我找到了這篇文章,但上面寫着,我需要在類中編寫一個函數。

刪除對象的私有屬性

我的問題是,是否可以在課堂外將其刪除? 因為當我在類中刪除它時,它總是被刪除,我只想在特定情況下刪除它。

這是一個Member對象數組。 對象的私有屬性只能通過其方法訪問。 您需要找到聲明類Member的文件。 然后添加一個公共類方法來執行unset 例如,

class Member {

  // ...
  public function unsetProjects()
  {
    unset($this->projects);
  }

}

那么你應該能夠做到這一點:

foreach ($array as $value) {
  $value->unsetProjects();
}

你應該使用 getter 和 setter

foreach ($array as $value) {
      dump($value->getProjects());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM