A
A
Alexey Konovalov2020-04-16 01:30:09
PHP
Alexey Konovalov, 2020-04-16 01:30:09

Is it correct to consider static methods global along with their classes?

Hello! I read the documentation, but I still don't understand. If I create a class with static methods and a static parameter like this:

class Speedbar{

  private static $data = [];
  
  public static function getData(): array
  {
    return self::$data;
  }
  
  public static function setData(array $data): void
  {
    self::$data = $data;
  }
  
}


Will I be able to call and change it from any part of the web application? (taking into account the autoloading of classes)
I tried and indeed, wherever I change the data parameter , in any php file it remains already changed.
Then it is not clear why singltone is needed if the class is already unique using only static methods

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Gordinskiy, 2020-04-16
@DmitriyGordinskiy

Regarding Singletone.
Static methods cannot be declared in an interface, hence you are tied to a specific implementation. There is no such problem with singleton.
UPD : as indicated in the comments, it can still be done.
Static methods are harder to code for tests. With a singleton, everything will be easier here too.

F
FanatPHP, 2020-04-16
@FanatPHP

Then it is not clear why singleton is needed if the class is already unique using only static methods

A very old question.
The singleton has nothing to do with the state of the class, only the number of instances. A singleton can only have one. This is such a crutch for procedural programming, for those who do not know how to OOP.
With normal OOP, a singleton is not needed, since the programmer is able to control how many and what objects are created for him, and not try to create a new object if the desired one has already been created.
Is it correct to consider static methods global along with their classes?

Correctly. This is shitty code, with very few exceptions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question