Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we use static calls in PHP?

Tags:

oop

php

static

Why should we use static variables or static calls to static methods in PHP5? Maybe to improve performance?

like image 961
Blackbeard Avatar asked Dec 04 '22 14:12

Blackbeard


2 Answers

We use static class variables to share data between all the instances of the class, and we use static methods (preferably private static) to compute something required for the class functionality, but independent of the class instance state ($this).

Performance is really not the reason for the existence of static-s. It's more like a side effect.

like image 198
Ivan Krechetov Avatar answered Dec 28 '22 17:12

Ivan Krechetov


Using static classes allows you to better organise code and functions that don't need to be represented by it's own instance. For example factory classes, helper classes, ulitily classes etc.

So for example, you could have a set of utility functions that manipulate numbers. Putting these in a static class "Math" allows you to group them together.

like image 36
JonB Avatar answered Dec 28 '22 18:12

JonB