0

Just startet to feel the real usefulness for classes and methods (Object Oriented Programming) in PHP. However I still lack the understanding and experience declaring methods and variables the proper way.

I what cases should I declare a method/variable static VS declaring it non-static? What questions do I ask myself to answer this question?

OnklMaps
  • 807
  • 8
  • 17
  • Have you done any research at all? A good start would be searching for something like _"When should I use static methods in PHP"_. First hit was a SO post: https://stackoverflow.com/questions/33705976/when-should-i-use-static-methods – M. Eriksson Sep 22 '17 at 23:39
  • @MagnusEriksson I have! However, in some sense I do see the difference, for example that you can call the static method directly without creating an instance. But is this only to save a line of code? `$myClass = new myClass(); $myClass->method();` vs only calling the method `myClass::method()`` – OnklMaps Sep 22 '17 at 23:48
  • No, it's not just that. There are many differences, just like the post i linked to explains. – M. Eriksson Sep 22 '17 at 23:50

1 Answers1

1

Static means that you can access the functions without first creating an instance of the class. This makes it a lot like a normal function. You tend to make functions static if you want to group functions together that are related, but do not need a specific instance of the class to run.

Non-static members require an instance of the class. Typically you will use this.

If we have a class Circle and it has function area(), then it would be non-static as it needs a specific circle to find the area of. Now imagine we have a PrintText class with a printBold() function. We don't need an instance since it only depends on the inputs. However it is convenient to have the PrintText class because we could have printBold(), printItalics(), etc.

Dylan
  • 41
  • 6