Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static modifier in PHP

Tags:

oop

php

static

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why? Hence my question:

What are the best practices regarding using static methods in PHP?

When would one want to use them and when would one shouldn't use them?

What are specific difference in how runtime handles static methods? Do they affect performance or memory footprint?

like image 667
Alex N. Avatar asked Aug 22 '09 19:08

Alex N.


People also ask

When should I use static methods in PHP?

When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.

Why do we need static class in PHP?

Static class is used for a single instance of that class whereas instantiated class is used when more than one instance is required. Static class contains static variables and static methods whereas instantiated class contains non-static variables and non-static methods.

When should you used static method?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

Why we should use static keyword?

The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.


1 Answers

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why

PHP didn't have namespaces before 5.3, so all function/variables would be in global scope unless they belonged in some class. Putting them in a class as static members is a workaround for not having namespaces (and that's probably why you saw them in "significant" number)

Generally, they are used for functions that aren't much useful in individual objects, but has some use at class level (as said in other answers)

like image 93
Imran Avatar answered Oct 12 '22 09:10

Imran