Why, in this code

<?php class Orator { private $name; function __construct($name){ $this->name = $name; echo 'Π‘ΠΎΠ·Π΄Π°Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ ' . $this->name . '<br>'; } function __destruct() { echo 'Π£Π½ΠΈΡ‡Ρ‚ΠΎΠΆΠ΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ ' . $this->name . '<br>'; } } function outer(){ $obj = new Orator(__METHOD__); inner(); } function inner(){ $obj = new Orator(__METHOD__); echo 'Π’Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, вбрасываниС!<br>'; throw new Exception('Hello'); } echo 'Начало ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹<br>'; try { echo 'Начало try-Π±Π»ΠΎΠΊΠ°<br>'; outer(); echo 'ΠšΠΎΠ½Π΅Ρ† try-Π±Π»ΠΎΠΊΠ°<br>'; } catch (Exception $e) { echo 'Π˜ΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅: ' . $e->getMessage() . '<br>'; } echo 'ΠšΠΎΠ½Π΅Ρ† ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹<br>'; 

the object is not immediately destroyed? After all, after the constructor, the destructor is immediately specified.

Now it works like this:

 Начало ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹ Начало try-Π±Π»ΠΎΠΊΠ° Π‘ΠΎΠ·Π΄Π°Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ outer Π‘ΠΎΠ·Π΄Π°Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ inner Π’Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, вбрасываниС! Π£Π½ΠΈΡ‡Ρ‚ΠΎΠΆΠ΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ inner Π£Π½ΠΈΡ‡Ρ‚ΠΎΠΆΠ΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ outer Π˜ΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅: Hello ΠšΠΎΠ½Π΅Ρ† ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹ 

And I wonder why it works wrong?

 Начало ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹ Начало try-Π±Π»ΠΎΠΊΠ° Π‘ΠΎΠ·Π΄Π°Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ outer Π£Π½ΠΈΡ‡Ρ‚ΠΎΠΆΠ΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ outer Π‘ΠΎΠ·Π΄Π°Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ inner Π£Π½ΠΈΡ‡Ρ‚ΠΎΠΆΠ΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ inner Π’Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, вбрасываниС! Π˜ΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅: Hello ΠšΠΎΠ½Π΅Ρ† ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΡ‹ 
  • Because the object lives inside the area. while the region is active, the object lives ... when inside an outer call occurs, then, in fact, outer has not yet completed its work. Because There is a sequential processing of instructions .... And outer waits for completion in inner. As soon as the instructions passed to inner, the context returns to outer and only after that the object is destroyed .... if you put inner() after outer() you will see that outer will die before the turn of the method of inner() - Alexey Shimansky
  • four
    Π’Π΅Π΄ΡŒ послС конструктора, сразу ΡƒΠΊΠ°Π·Π°Π½ дСструктор. - And it would be strange if the implementation of methods in a class depended on their consistent location within the class. It’s just hard to imagine a class with 20 methods in which the higher the method, the first it works :)) I ranked the destructor second in order and you laugh at colleagues :)) - Alexey Shimansky

1 answer 1

You have the __destruct () method declared after the __construct () method, but this does not mean that they will work in turn.

Conventional methods work when they are called, and you can call them in any order and as many times as you like. In your case, __destruct () and __construct () are not explicitly called __construct () - when creating an object, __destruct () is called when an object is destroyed.