John Davidson

php - Is a class destruct a reliable way to always execute something at script end?

0 comments
Message:


I was thinking about doing something like this


<?php
/** efficient log writing system */
class LogSystem{

const LOG_FOLDER = "./whatever/";

protected $logRows = [];

public function log( string $what ){
$this->logRows[] = date("h:i:s").": ".$what;
}

function __destruct(){
if( !empty($this->logRows) ){
$filename = date("Y-m-d").".log";
$cnt = implode( PHP_EOL, $this->logRows ).PHP_EOL.PHP_EOL;
file_put_contents( Self::LOG_FOLDER.$filename, $cnt, FILE_APPEND );
}
}
}

Today the server this would be executed on stopped because of a very unusual hardware problem. This got me thinking: can I reasonably be sure that the __destruct of this class will always manage to write its array?



My Answer:
Yes, using a class destructor is a reliable way to ensure that a certain action is always executed at the end of a script. The destructor method in a class is automatically called when the object is destroyed or goes out of scope, which typically happens at the end of the script execution.

Here is an example of how you can use a class destructor to execute something at the end of a script:

php
class MyClass {
public function __construct() {
// Constructor code
}

public function __destruct() {
// Code to be executed at the end of the script
echo "Script has ended";
}
}

$myObject = new MyClass();

// Rest of the script

// The destructor of MyClass will be automatically called at the end of the script


In this example, the `__destruct` method of the `MyClass` class will be automatically called at the end of the script, ensuring that the message "Script has ended" is always displayed.

Rate this post

5 of 5 based on 7480 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us