簡體   English   中英

PHP object 的屬性可以是數組嗎? 如果是這樣,我如何從 object 中添加它?

[英]Can a property of a PHP object be an array? And if so how do I add to it from within the object?

I have an object to represent the combination of data from three tables, I'm trying to make this object as universal as possible so changes in the DB structure don't have to be reflected in the object and allowing the object to edit the 3表分開而不是制作冗長復雜的 SQL 連接語句。

由於 object 代表一個數據庫表,因此需要/可接受公共屬性,我試圖在構造函數中動態生成它們,但為信息所屬的不同數據庫表保持屬性分開。(這樣當我 go 更新一個表,必須檢查更改然后發送到更新的信息不會與其他表中的屬性混合)

我的第一個想法是將每個表保存在每個表的 object 屬性內的數組中......但是向 arrays 添加數據的幾次嘗試都是空白的,所以這要么是不可能的,而且我只是偷偷摸摸過去的語法錯誤有道理,否則我做錯了。

有什么幫助嗎?

class MemberObject
{
  private $dbc;
  private $memberID;
  private $membersTable;
  private $affiliatesTable;
  private $clientsTable;

// Each DB held in own array
  public $member = array();
  public $affiliate = array();
  public $client = array();

  public function __construct(PDO $dbc, $memberID)
  {
    $this->dbc = $dbc;
    $this->memberID = $memberID;
    $this->membersTable = new DatabaseTable($dbc, 'member', 'memberID');
    $this->affiliatesTable = new DatabaseTable($dbc, 'memberAffiliated', 'memberID');
    $this->clientsTable = new DatabaseTable($dbc, 'memberClient', 'memberID');
    $thisMember = $this->membersTable->findById($this->memberID);
    $this->populateData($thisMember, $this->member);

    if ($thisMember = $this->affiliatesTable->findById($this->memberID))
    { // IF get member from affiliatesTable
      $this->populateData($thisMember, $this->affiliate);
    }

    if ($thisMember = $this->clientsTable->findById($this->memberID))
    { // IF get member from clientsTable
      $this->populateData($thisMember, $this->client);
    }
  }

  private function populateData($dataArray, $targetTable)
  {
    foreach ($dataArray as $key => $value)
    {
      $targetTable[$key] = $value;
    }
  }

  public function saveEdit()
  {
    $membersTable->save($this->member);
    if (isset($this->affiliate['affiliateID']))
    {
      $affiliatesTable->save($this->member);
    }
    if (isset($this->client['clientID']))
    {
      $clientsTable->save($this->member);
    }
  }
}```

I don't know why but sending the object property to the object function with $this->member wasn't working so changing the parameter in the function to a string and using this in the function actually targeted the array as expected:

$this->{$targetTable}[$key] = $value;

暫無
暫無

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

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