I ask those who know php to help, I study php, for me, in general, the first programming language, so the process constantly raises so stupid questions that the Internet doesn't even seem to answer them. He reached the classes and fell into a stupor. Help me to understand.
There is such an example from the textbook:

<?php ## Использование статических членов класса. class Counter { // Скрытый статический член класса - общий для всех объектов. private static $count = 0; // Конструктор увеличивает счетчик на 1. Обратите внимание // на синтаксис доступа к статическим переменным класса! public function __construct() { self::$count++; } // Деструктор же - уменьшает. public function __destruct() { self::$count--; } // Статическая функция, возвращает счетчик объектов. public static function getCount() { return self::$count; } // Как видите, установить счетчик в произвольное значение // извне нельзя, можно только получить его значение. Вот он, // модификатор private "в действии". } // Создаем 6 объектов. for ($objs = [], $i = 0; $i < 6; $i++) $objs[] = new Counter(); // Статические функции можно вызывать точно так же, как будто // бы это - обычный метод объекта. При этом $this все равно // не передается, он просто игнорируется. echo "Сейчас существует {$objs[0]->getCount()} объектов.<br />"; // Удаляем один объект. $objs[5] = null; // Счетчик объектов уменьшится! echo "А теперь - {$objs[0]->getCount()} объектов.<br />"; // Удаляем все объекты. $objs = []; // Другой способ вызова статического метода - с указанием класса. // Это очень похоже на вызов функции из библиотеки. echo "Под конец осталось - ".Counter::getCount()." объектов.<br />"; ?> 

I'll start from the end:

  • $ objs [0] -> getCount () - why is 0 specified?
  • $ objs [5] = null; - I understand that the null value is assigned to the fifth element in the $ objs array, but in fact, the entire array seems to be cleaned up, how does it work?
  • $ objs [] = new Counter (); - I understand that an array of $ objs is created which uses the class Counter. But what does it mean? As an array can be equal to a class, there is no exact value there. Only a couple of functions.
  • public function __destruct () {self :: $ count--; } - as I understand it, reduces $ count by 1, but how does it start ?? What drives this feature?
  • public function __construct () {self :: $ count ++; } - Same thing, only increments the counter by 1, the same question that triggers this function?

    3 answers 3

    $ objs [0] -> getCount () - why is 0 specified? Because when recording

     $objs[] 

    An element is added to the array. If you do not specify a key, then it is added in order as a number. Since this operation was performed once, the cell key will be "0", from which the element is taken.

    Note: However, such a call is not entirely correct, because An attempt is made to call a static method in a non-static context. Before PHP7, this is a ride, but not in later versions. because this is not right.

    $ objs [5] = null; - I understand that the null value is assigned to the fifth element in the $ objs array, but in fact, the entire array seems to be cleaned up, how does it work?

    Why should the entire array be cleaned? After all, there is also a clearly indicated cell with the index 5.

    $ objs [] = new Counter (); - I understand that an array of $ objs is created which uses the class Counter. But what does it mean? As an array can be equal to a class, there is no exact value there. Only a couple of functions.

    When spelled

     new Counter() 

    then an instance of the class is created and placed in some variable. In this case, instances are created in a loop and are added to the cells of the array. Therefore, in each cell lies an instance of the class Counter

    public function __destruct () {self :: $ count--; } - as I understand it, reduces $ count by 1, but how does it start ?? What drives this feature?

    For example, deleting an object, as an example:

     $objs[5] = null 

    or if the object is no longer used and the GC decides to remove it as garbage. For example, this may be if work with an object occurs in some function / method

     function myMethod(){ $counter = new Counter(); } 

    After practicing the myMethod method, the $counter variable is not used anywhere and is killed. What causes the destructor

    public function __construct () {self :: $ count ++; } - Same thing, only increments the counter by 1, the same question that triggers this function?

    It is logical that the creation of an object causes this, that is, this line:

     new Counter() 

    More information about the magic methods, which include __construct and __destruct is written in the documentation: http://php.net/manual/ru/language.oop5.magic.php

    • thanks for the answer, but did not understand about $ objs [0] -> getCount () because the example shows the number of objects, that is, as I understood it, 6 variables were created in the array, we call 0 here, and we get the number 5, instead of 1? Shouldn't it be $ objs [] -> getCount ()? - Paul Wall
    • @PaulWall not. I wrote that in your case the objects are stored in the cells of the array. This means that in order to call at least some method on an object, it is necessary at first to refer to the index, for example, $obj[3] and call the method $obj[3]->someMethod . And since the getCount method returns a static variable, it will be the same for all instances and therefore you can call getCount on any object. In this case, this is the one that lies in the cell "0" - Sergey Mishin
    • aaaaaa finally understood everything =) otherwise it was not written anywhere)) - Paul Wall

    Honestly, you are very bad with theory, and even with the choice of the first programming language (for example, I would recommend some Python).
    I will explain "on the fingers":

    1. Static variables are variables that exist throughout the work of the entire program, they store the value of one for all objects of the class (which can also be changed), you can read more here.
    2. null is a keyword that is responsible for freeing memory, thereby destroying the array element / s
    3. $objs[] = new Counter() - in a loop adds an object of type Counter to the array
    4. The constructor is called when an object is created, and destructors when an object is destroyed, you can read more about them here.

      1) Generally an interesting way to call a static function. I think when using somewhere in real projects it will create only misunderstandings (since this is a function of the class and the object does not really have such a method). It would be much clearer to make the call so Counter::getCount() .

      2) Firstly, in this case, the 6th element is “killed” (the numbering of the arrays starts from 0 ). It is not entirely clear what you mean by the word cleared . Regular arrays (and php are also associative ) visually look like this:

      0 1 2 3 4 5 ---> array indices

      abcdef ---> array values

      those. You, when referring to the 5th element, get the letter f , when referring to 2 - c , etc. You can look at them as on a shelf with tool boxes, where each box on the shelf is signed.

      3) the new keyword creates a new class object Counter , which can do and use what you declared in the Counter class without the static modifier. In this example, in the Counter class, there are no non-static user-defined methods (the constructor and destructor are, how to properly call ... built-in methods or something). Try to declare your method in your class, for example:

       public function sayHello(){ echo 'Hello!'; } 

      Then you can call it on the object ( objs[0]->sayHello() , but you cannot call it in a static context ( Counter::sayHello() //будет ошибка ).

      4, 5) In this place increment and decrement operations are used. You can read about these operations, for example, here .

      • Thanks for the answer, but if I create a public function and call it, why exactly 0 is specified in objs [0] -> sayHello () - Paul Wall
      • @PaulWall because the author of the book you are reading reads like this;) Actually, you can call this function (in the context of an AOI is a method) on any object of this class - Ep1demic