Initialize a class that cannot be used

Suppose I am initializing a class, but I have a convention in my script, which could mean that the methods of the class will never be used.

Example:

$rr = new RecipientRepo($db);

if ($_GET['action'] == 'test1') {
    $rr->showForm1();
}
else if ($_GET['action'] == 'test2') {
    $rr->showForm2();
}

      

If this condition is not met, the class methods will never be called.

Is this bad practice? I would prefer this to initialize the class in every single condition.

Any answers would be appreciated.

+3


source to share


2 answers


Initialize the class only if the key is set to $_GET

. You can do it -

if (!empty($_GET['action'])) {

    $rr = new RecipientRepo($db);

    if ($_GET['action'] == 'test1') {
        $rr->showForm1();
    }
    else if ($_GET['action'] == 'test2') {
        $rr->showForm2();
    }

}

      



If you want to make it more specific then

if (!empty($_GET['action']) && in_array($_GET['action'], array('test1', 'test2'))) {

      

+2


source


If the initialization of the class is resource intensive, you can initialize it depending on whether you need it. If the object RecipientRepo

is closely related to the view form, you can even add a static method to the object to determine if it needs to be created:

public static function formPosted() {
  return (
    isset($_GET['action']) &&
    in_array($_GET['action'], array(
      'test1',
      'test2'
    ))
  );
}

      

Then in your main form, you can call it to determine if the object needs to be instantiated:



if (RecipientRepo::formPosted()) {
  $rr = new RecipientRepo($db);
  if ($_GET['action'] == 'test1') {
    $rr->showForm1();
  }
  else if ($_GET['action'] == 'test2') {
    $rr->showForm2();
  }
}

      

Wrapping this logic in a method ensures that you only instantiate the object under the right conditions. It also encapsulates the logic for determining when to do this in an easy-to-read structure.

+1


source







All Articles