0

I have declared a PHP magic function __destruct in child class, when an object from this child class is called it also calls the __destruct from the parent class in addition to the __destruct from the child class.

How do I make sure that only the __destruct in the child class is called. I do not want to use access modifiers too because I might be creating another child class.

  • 1
    This might be an opinion, but I don't think you should try this. It's a sign of bad OOP design if you have to. Perhaps you could convince me that I am wrong with a good example? – KIKO Software Nov 18 '22 at 16:46
  • Why do you want to suppress the parent class behaviour? Maybe it does something important? As mentioned above, if it's causing you a problem you might want to re-think your design, but it's hard to give definitive advice without any code or context – ADyson Nov 18 '22 at 16:52
  • Yes, you probably have to redesign it somewhat. The parent class shouldn't (always) be doing things that a child class doesn't want/need. – KIKO Software Nov 18 '22 at 16:57
  • 6
    I'm confused -- if you have __destruct() in the parent and __destruct() in the child, then the parent won't get called unless you explicitly put `parent::__destruct();` in the child. So just... don't do that? Am I misunderstanding your design? – Alex Howansky Nov 18 '22 at 16:59
  • Oh okay , thanks maybe I should re-design my code. – Andoh Francis Nov 18 '22 at 17:02
  • Although using a destructor is totally valid, I think the vast majority of examples that I've seen of people using them seem to be based on a misunderstanding of object life cycles, most commonly [database connections](https://stackoverflow.com/a/67644892/231316). I'm not saying your code is wrong (especially since we haven't seen it), I'm just noting past experiences. – Chris Haas Nov 18 '22 at 18:12
  • @AlexHowansky Yes, you're right. It works the same as `__construct()`. I went along with the question, but I should have checked. I did now: https://3v4l.org/aYH1L – KIKO Software Nov 18 '22 at 18:21

0 Answers0