CodeIgniter Forums
General use class: static or not? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: General use class: static or not? (/showthread.php?tid=76373)



General use class: static or not? - YanKleber - 05-06-2020

I have this generic class with some small functions to be used by the whole application.

I would like to know what is considered a 'better practice' in this case: make the methods as static and call them directly or instantiate the class into the controller?

Huh 

Thanks!


RE: General use class: static or not? - php_rocs - 05-06-2020

@YanKleber,

Is this for CI3 or CI4?


RE: General use class: static or not? - YanKleber - 05-06-2020

(05-06-2020, 02:28 PM)php_rocs Wrote: @YanKleber,

Is this for CI3 or CI4?

It's CI4. I thought that being basically plain PHP it wouldn't matter, sorry.


RE: General use class: static or not? - php_rocs - 05-06-2020

@YanKleber,

While yes they both are based on PHP, there are differences between CI3 and CI4. Here is some documentation that may assist you https://codeigniter.com/user_guide/general/modules.html#code-modules.


RE: General use class: static or not? - YanKleber - 05-07-2020

I see... well I am not sweating too much about this... I tested and both methods work without any noticeable difference. I just was imagining if one of them could be considered more "correct". Thanks!

Cool


RE: General use class: static or not? - nicojmb - 05-07-2020

(05-07-2020, 08:53 AM)YanKleber Wrote: I see... well I am not sweating too much about this... I tested and both methods work without any noticeable difference. I just was imagining if one of them could be considered more "correct". Thanks!

Cool

Hi, if is CI4 make your class as service and you call directly like this:

PHP Code:
$class = \Config\Services::yourClass();
$class->yourVariable;
$class->yourMethod();
or
$variable = \Config\Services::yourClass()->yourVariable;
or
$method = \Config\Services::yourClass()->yourMethod(); 

Here are docs:

https://codeigniter4.github.io/userguide/concepts/services.html


RE: General use class: static or not? - YanKleber - 05-07-2020

Cool nicojmb I'll take a look, as well as the docs pointed by php_rocs either!

Smile


RE: General use class: static or not? - php_rocs - 05-07-2020

@YanKleber,

Here is some reading that discusses the differences of CI3 and CI4 (more focus on CI4): https://codeigniter.com/user_guide/installation/upgrade_4xx.html