Skip to content
Advertisement

Learning how to refactor PHP code

I’m using PHP 5.2.9 at the very moment. Is there a way to refactor this code this way it’s easier to read and better organized?

  if ($is_read_only == true) {
      echo ($affiliate['affiliate_gender'] == 'm') ? MALE : FEMALE;
  } elseif ($error == true) {
      if ($entry_gender_error == true) {
            echo tep_draw_radio_field('a_gender', 'm', $male) . '  ' . MALE . '  ' . tep_draw_radio_field('a_gender', 'f', $female) . '  ' . FEMALE . ' ' . ENTRY_GENDER_ERROR;
      } else {
            echo ($a_gender == 'm') ? MALE : FEMALE;
            echo tep_draw_hidden_field('a_gender');
      }
  } else {
      echo tep_draw_radio_field('a_gender', 'm', $male) . '  ' . MALE . '  ' . tep_draw_radio_field('a_gender', 'f', $female) . '  ' . FEMALE . ' ' . ENTRY_GENDER_TEXT;
  }

Advertisement

Answer

It depends on what exactly you mean by “compress“?

Since you haven’t clarified you’re getting a basic response.

Removing spaces:

If you are expecting to speed up your code in some way, don’t bother. Compressing (making smaller/removing spaces in) a php file won’t speed up it’s execution time. PHP reads the file every time, compiles it into bytecode and runs it. Doing this will make your eyes bleed as well as those of your colleagues. Just don’t do it!

For readability/usability:

Then you’d be wise to space your code/classes/functions accordingly into blocks that make sense and are easily readable. This won’t just help you but those who work alongside you. Use set indent levels, spacing/bracket/nesting styles etc.

For code performance:

There are a myriad of ways to improve code (the classes/functions/loops/connections/statements) both in visual form and for the sake of code performance – which can be profiled/tested using a wide variety of tools.

Hope this helps as a pointer.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement