Best practices question: Is there anything improper about creating a new object within another class method? I have a small example below:
public function export() {
$orders = new Orders($id);
$all_orders = $orders->get_all_orders();
}
Best practices question: Is there anything improper about creating a new object within another class method? I have a small example below:
public function export() {
$orders = new Orders($id);
$all_orders = $orders->get_all_orders();
}
The example you gave is perfectly acceptable.
If for example, you were instantiating the same object in all of your methods then you could store the object as a property instead.
Example: The Orders object is instantiated in the constructor and stored as a property.
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();
}
}
Passing Order object in constructor would be a better approach in my opinion. That would make testing easier.
It all depends on the big picture of the problem, obviously the id needs to be passed to Order object somewhere else:
class Something
{
protected $orders;
public function __construct(Order $order)
{
$this->orders = $order;
}
}