4

Should I use classes with static functions or namespaces to better organise a PHP project growing in size?

I come from a Java background and like having static variables/functions available.

hakre
  • 193,403
  • 52
  • 435
  • 836
JackMahoney
  • 3,423
  • 7
  • 32
  • 50
  • 1
    Well, all my personal dependency injection, anti-static dogma aside ... organization and name collision avoidance is exactly what namespaces are for. You should prefer them for organization over globally accessible functions and class methods. –  Feb 17 '12 at 03:17
  • 4
    If you came from java - it is strange that you ask such questions – zerkms Feb 17 '12 at 03:17
  • 1
    Why strange? I like being able to organise methods so I can call Cities.getCitiesArray() etc – JackMahoney Feb 17 '12 at 03:48
  • 1
    php namespaces are a nightmare compared to other languages like c#, python or java but i could no imagine simulating the behaviour of namespaces with static functions... for me it's a bad idea. If you want to grow use namespaces. – Tony Feb 17 '12 at 13:55

2 Answers2

3

The 2 features are completely different from each other.

The static keyword is to make a property or method available without an actual class instance. http://php.net/manual/en/language.oop5.static.php

On the other hand Namespaces are for organization and avoiding naming collisions. http://www.php.net/manual/en/language.namespaces.rationale.php

topdown
  • 456
  • 3
  • 6
  • Thanks for the answer but I don't think I worded the question correctly. Any way this helped – JackMahoney Feb 17 '12 at 03:49
  • 7
    Perhaps, but the way the OP was talking about using a class + static methods, there isn't much difference. People were using abstract classes as "namespaced" method/constant containers long before PHP had real namespaces. – FtDRbwLXw6 Feb 17 '12 at 04:17
0

Yep you can set the variable as static.. or you can look at class const as well.. this way you are avoiding global variables, can determine from which class you are accessing, and won't need to instantiate the class to get the value..

dmb
  • 1,066
  • 1
  • 8
  • 10