php - 在不同类型的对象之间传递私有属性
问题描述
我有以下对象,我想让它们相互合作。用户可以在不同的时间创建与其他对象分开的每个对象。最后的用法是用户将所有对象链接在一起以组成最后一个对象。
发票.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);此外,他们唯一能继承的就是一块田地……这对我来说就像是一种浪费。
我想把它们更像是一些组件,假设它是可能的。
解决方案
您可以让 InvoiceHeader 持有一个 TransmissionData 对象(由您当前的 set 方法设置),并让 TransmissionData 对象公开一个方法来获取生成的 XML,这样您就不需要公开原始属性,只需要公开生成的 XML 块?
类似地,Invoice 可以包含 Invoice 标头对象属性,并且 InvoiceHeader 公开了另一种方法来获取所需的 XML,再次在核心类中保持属性编辑并且仅以可消费格式公开数据?
如果在任何时候都需要将多个 XML 部分放入最终结果中的不同位置,您可以为每个所需的块公开许多方法。
我不会尝试在这里输入 php 代码 - 我生疏了!
推荐阅读
- scala - 列出Scala中非默认文件系统上的文件
- java - 我应该如何估计Java中for循环的时间函数(T(N))?
- sql - SQL从xml解析多个字段
- kubernetes - 配置 k8s 以停止在旧 pod 上接受请求,一旦至少有最小预期数量的新 pod 可用
- asp.net-core - 如何动态注册像asp netcore这样的依赖项使用IOption
- sql-server - 使用 polybase 和 Azure blob 存储指向特定位置
- python - 在 Keras 中制作 LSTM 模型时出现 TypeError
- python - 在 Scapy 中更改数据包字节序
- basic - 在 Visual Studio 2017 Visual Basic 中,我收到“预期语句结束”错误
- css - 在最小化图像从位置 CSS 下降