Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper Class in PHP - static method vs standard function

Tags:

oop

php

Which is the best/right way if I want to create a Helper class in PHP?

A Helper class that contains static methods like this:

<?php
class Helper {

   static function helpThis() {
      // code
   }

   static function helpThat() {
      // code
   }
}
?>

Or

Create a PHP file with a bunch of functions like this:

<?php
   function helpThis() {
      // code
   }

   function helpThat() {
      // code
   }
?>
like image 953
Ahmad Avatar asked Oct 29 '25 17:10

Ahmad


2 Answers

I'd suggest creating a class.

This way you can save yourself from adding include helper.inc.php everytime before using these functions.

Class on the other hand can be autoloaded: Helper::helpThis() and that's it.

like image 91
Stanislav Shabalin Avatar answered Oct 31 '25 07:10

Stanislav Shabalin


I guess it's always 'better' to put the methods in a class. Not only does it look better, but when using classes it's easier to know what every function/method does. You could for example create a main helper class and several other helper classes that derive from the main class. Everything is in place then and clear to understand what it does. ;)

like image 40
Abbas Avatar answered Oct 31 '25 07:10

Abbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!