Php Destructors

Viewed 19294

Please give me some real life examples when you had to use __destruct in your classes.

12 Answers

Here's a rather unusual use case for destructors that I think libraries such as pest are using to combine method chaining with functions or in other words, to achieve fluent interface for functions, Which goes like this:

<?php

class TestCase {
    private $message;
    private $closure;
    private $endingMessage;
    public function __construct($message, $closure) {
        $this->message = $message;
        $this->closure = $closure;
    }

    public function addEndingMessage($message) {
        $this->endingMessage = $message;
        return $this;
    }
    private function getClosure() {
        return $this->closure;
    }
    public function __destruct() {
        echo $this->message . ' - ';
        $this->getClosure()();
        echo  $this->endingMessage ? ' - ' . $this->endingMessage : '';
        echo "\r\n";
    }
}

function it($message, $closure) {
    return new TestCase($message, $closure);
}



it('ok nice', function() {
    echo 'what to do next?';
});//outputs: ok nice - what to do next?

it('ok fine', function() {
    echo 'what should I do?';
})->addEndingMessage('THE END');//outputs: ok fine - what should I do? - THE END
Related