Which is better in Object-Oriented Programming?

Which is better doing something like this:

<?php
namespace website_project\calendar;
use DateTime;
class Controls {

  public $returnDate;
  public $displayControls;
  public $returnControls;
  protected static $todaysDate;
  protected static $page;
  protected static $varPage;
  protected static $next;
  protected static $previous;
  protected $urlDate;
  protected $currentMonthPositon;
 

  public function __Construct($page = 0) {
    $this->returnDate = $this->todaysDate($page);
    $this->returnControls = $this->calButtons();
  }
  
  public function setMonth($page) {
      return self::__construct($page);
  }

where you can just do the following without creating an instance?

$controls = new Controls();
$controls->setMonth($page);

or just doing it this way:

$controls = new Controls($page);

It’s probably a stupid question, but to me doing way it the last creates a new instance every time (am I right thinking this way?). Whereas, the first one doesn’t. So my question which one is better? Or does it really matter?
Thanks John

The second way is better, since your class has a dependency on $page. This dependency is required, not optional. For required dependencies, you should use constructor injection. For optional dependencies, you may use setter injection.

1 Like

Thank You, that cleared it up tremendously and it cleaned up my classes.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.