最佳做法:类方法中的新对象实例化


Best practices: New object instantiation within a class method

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

public function export() {
$orders = new Orders($id);
$all_orders = $orders->get_all_orders();
  }

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

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

示例: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();
    }
}
在我看来,

构造函数中的传递顺序对象将是一种更好的方法。这将使测试更容易。

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

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