PHP 静态与实例

标签 php oop object static

我正准备编写一个方法将一些账单数据转换成发票。

假设我有一个对象数组,其中包含创建调用项所需的数据。

While in the billing controller 以下哪种方式是正确的

$invoice = new Invoice();
$invoice->createInvoiceFromBilling($billingItems);

然后在发票类

Public Function createInvoiceFromBilling($billingItems)
{
    $this->data = $billingItems;

Invoice::createInvoiceFromBilling($billingItems)

然后在发票类

Public Function createInvoiceFromBilling($billingItems)
{
    $invoice = new Invoice();
    $invoice->data = $billingItems;

哪种方式才是正确的方式?

问候

最佳答案

正如 tereško 在上面的评论部分中指出的那样,您应该考虑使用 Factory pattern .来自链接源的一个很好的(简单的)基于真实世界的例子:

<?php
class Automobile
{
    private $vehicle_make;
    private $vehicle_model;

    public function __construct($make, $model)
    {
        $this->vehicle_make = $make;
        $this->vehicle_model = $model;
    }

    public function get_make_and_model()
    {
        return $this->vehicle_make . ' ' . $this->vehicle_model;
    }
}

class AutomobileFactory
{
    public function create($make, $model)
    {
        return new Automobile($make, $model);
    }
}

// have the factory create the Automobile object
$automobileFactory = new AutomobileFactory();
$veyron = $automobileFactory->create('Bugatti', 'Veyron');

print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"

如您所见,实际创建 Automobile 实例的是 AutomobileFactory。

关于PHP 静态与实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263322/

相关文章:

php - Sweetalert 对数据库进行删除操作

php - 为什么有些字符无法从 Linux/Bash 环境变量中提取到 PHP 中?

php - 如何从一个类中获取常量,排除所有可能从 parent 那里继承下来的常量?

oop - 使用面向对象的分析和设计对电梯进行建模

javascript - 如何访问此对象的属性?

javascript - 将鼠标事件绑定(bind)到 JavaScript 对象

php - 使用 MongoDB 和对象数组进行 Laravel 单元测试

php - 编译成 PHP 的编程语言?

python - 如何用不同的对象替换 __init__() 中的实例?

javascript - 如何根据键将对象数组拆分为不同的对象