Answer the question
In order to leave comments, you need to log in
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
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'
]);
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question