0

I got really confused with static and non-static functions and class properties when I was trying to run my website.

Can someone explain whether it is better to have the whole website written using Static functions rather than using the non-static methods? I can't find much of this on google.

YakovL
  • 7,557
  • 12
  • 62
  • 102
mkram0
  • 42
  • 3

4 Answers4

1

There is a school of thought according to which statics are harmful and should be avoided, because they create binds between classes which are too rigid. E.g. if you have classes A and B which call each other's methods, and then subclass AA and BB from them, and expect AA to invoke the code of BB, that will work nicely if they only know about each other as instances, but it will fail for static calls which will still point to A/B.

At any rate, PHP's implementation of statics is quite bad. There is no late static binding before 5.3 (meaning that an object can't call its own static methods, making static functions farily useless in an OOP architecture), static functions cannot be called non-statically in strict mode, calling functions the wrong way will result in very weird errors, classes share their static variables with their parents... when uncertain, you should go with non-static IMHO.

Tgr
  • 27,442
  • 12
  • 81
  • 118
0

This really depends on how your application is designed. If the function can and will be called and without instantiating the class, then declare it as static. Otherwise, don't. In almost all cases you would be using a combination of the two, since using only static functions wouldn't make sense (you might as well write procedural code).

EdoDodo
  • 8,220
  • 3
  • 24
  • 30
0

It doesn't make sense writing OO code and using only static variables and methods. It would be same as writing procedural code. you can't benefit from all the functionality OOP gives only using static code.

I'm not saying that you mustn't use static methods or properties, but using them a lot is an indicator of a bad OO design.

Headshota
  • 21,021
  • 11
  • 61
  • 82
  • And using only non-static methods and properties is good right? – mkram0 Jul 03 '11 at 09:00
  • I would say that combination of both would be best. e.g. some design patterns strongly depend on static functionality, Singleton for instance. you must use static code only when it's necessary. – Headshota Jul 03 '11 at 09:13
0

If your method needs access to data in "this->", then you have to make it a non-static method. Then the object needs to be instantiated (via "new").

If all your method uses is data contained in function parameters, then consider making your method static. Or create a separate class with static methods only.

JSawyer
  • 110
  • 3
  • This answer highlights the difference only on a semantic level. It does not not address the downside of using static e.g. in test driven development. – k0pernikus Sep 02 '19 at 12:06