首页 > 解决方案 > 在不同类型的对象之间传递私有属性

问题描述

我有以下对象,我想让它们相互合作。用户可以在不同的时间创建与其他对象分开的每个对象。最后的用法是用户将所有对象链接在一起以组成最后一个对象。

发票.php

<?php
class Invoice
{
  private $header;
  private $xml;

  public function __construct()
  {
    // code that initializes $this XML tree (root)
  }

  public function setInvoiceHeader($invoiceHeader)
  {
       /* code that should merge $this->xml with the one from the $invoiceHeader param
       but I can't access it here because of private visibility and I would like to avoid
       the public visibility */
  }

  public function writeXMLDocument()
  {
    // code that returns the XML document
  }

}
?>

InvoiceHeader.php

<?php
class InvoiceHeader
{
  private $xml;

  public function __construct()
  {
    // code that initializes $this XML tree
  }

  public function setTransmissionData($transmissionData)
  {
    /* code that should merge $this->xml with the one from the $transmissionData param
       but I can't access it here because of private visibility and I would like to avoid
       the public visibility */
  }

}
?>

传输数据.php

<?php
class TransmissionData
{
  private $xml;
  private $transmissionIdNode;

  public function __construct()
  {
    // code that initializes $this XML tree
  }

  public function setTransmissionId($idCountry, $idCode)
  {
    // code that creates the XML node with the params
  }

}
?>

我找不到private在对象之间传递 $xml 的方法。

我想避免使用public可见性,因为我不希望用户可以访问低级实现。

我想避免使用继承和protected可见性,因为我认为这些对象没有太大的相关性(InvoiceHeader 不是 Invoice,TransmissionData 不是 InvoiceHeader);此外,他们唯一能继承的就是一块田地……这对我来说就像是一种浪费。

我想把它们更像是一些组件,假设它是可能的。

标签: phpclassoop

解决方案


您可以让 InvoiceHeader 持有一个 TransmissionData 对象(由您当前的 set 方法设置),并让 TransmissionData 对象公开一个方法来获取生成的 XML,这样您就不需要公开原始属性,只需要公开生成的 XML 块?

类似地,Invoice 可以包含 Invoice 标头对象属性,并且 InvoiceHeader 公开了另一种方法来获取所需的 XML,再次在核心类中保持属性编辑并且仅以可消费格式公开数据?

如果在任何时候都需要将多个 XML 部分放入最终结果中的不同位置,您可以为每个所需的块公开许多方法。

我不会尝试在这里输入 php 代码 - 我生疏了!


推荐阅读