A
A
Alexander Polyansky2015-07-11 02:02:51
PHP
Alexander Polyansky, 2015-07-11 02:02:51

What is static in PHP OOP?

Hello, please explain to a beginner what does the word static mean in PHP OOP? For what purpose is it used and why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-07-11
@Eclerr

To do this, you need to understand the difference between classes and objects. Here there are methods and properties of objects and there are methods and properties of classes. The latter are just static properties and methods. Hence all the features of their work and possible use cases. There can be only one class in our system, and there are many instances of this class (objects).
Typically, static methods are used as generators. That is, you call a static method of a class, and it gives you an instance of this class.

$foo = Singleton::instance();
$bar = AbstractFactory::create('bar');
$buz = Buz::fromArray([
    'many' => 'arguments', 'Buz' => 'has', 'private' => 'constructor'
]);

In PHP, they still like to use statics as a replacement for regular functions, due to the fact that we have autoloading for classes, but not for functions. Not to say that this is very good, I would even say that it is bad. Considering that there is composer now, and thanks to opcache, there is no overhead connection for each file request. In general, it's best to try to avoid using statics, or at least do anything complicated in static methods. And it’s better to always limit yourself to only cases for generating objects, here statics looks logical.
When viewed from the point of view of spawning static methods, we also need to know who to create. And here two keywords appear - self and static. Moreover, self is tantamount to writing the name of the class in which our static method is located and simply allows you to reduce duplication. static is much more interesting, since it points directly to the class from which the call was made. Let's say if you have inheritance, you can push the generating method into the base class, and then it's not a problem to find out who to create in principle.
class Foo {
    public static function createWithSelf() {
         // равносильно new Foo();
         return new self();
    }
    public static function createWithStatic() {
         // а тут мы пока не знаем кто такой этот static
         $foo = new static();
    }
}

class Bar extends Foo {}

$foo = Bar::createWithSelf(); // тут будет экземпляр Foo
$bar = Bar::createWithStatic(); // тут будет экземпляр Bar

L
Lesha Kiselev, 2015-07-11
@Yakud

php.net/manual/en/language.oop5.static.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question