1

最佳实践问题:在另一个类方法中创建新对象有什么不当之处吗?我在下面有一个小例子:

public function export() {

$orders = new Orders($id);
$all_orders = $orders->get_all_orders();

  }
4

2 回答 2

2

你给出的例子是完全可以接受的。

例如,如果您在所有方法中实例化同一个对象,那么您可以将对象存储为属性。

示例:Orders 对象在构造函数中实例化并存储为属性。

class Something
{    
    protected $orders;

    public function __construct($id)
    {
        $this->orders = new Orders($id);
    }

    public function export()
    {

        // use $this->orders to access the Orders object
        $all_orders = $this->orders->get_all_orders();
    }

}
于 2012-05-04T13:11:55.913 回答
0

在我看来,在构造函数中传递 Order 对象将是一种更好的方法。这将使测试更容易。

这一切都取决于问题的大局,显然 id 需要在其他地方传递给 Order 对象:

class Something
{    
    protected $orders;

    public function __construct(Order $order)
    {
        $this->orders = $order;
    }

}
于 2014-01-11T04:01:31.640 回答