Last active
March 15, 2020 10:38
-
-
Save SebSept/82c16be9b5ae643718b4228d23fd761f to your computer and use it in GitHub Desktop.
non verbose way to send output to stderr or stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
/** | |
* Writes messages to stderr or stdout. | |
* | |
* @author Sébastien Monterisi <https://gist.github.com/SebSept/> | |
* @throws FailureToWriteToFile | |
*/ | |
function stdErr(string $message): void { stdLog('php://stderr', $message); } | |
function stdOut(string $message): void { stdLog('php://stdout', $message); } | |
function stdLog(string $stream_path, string $message): void | |
{ | |
if (!file_put_contents($stream_path, $message.PHP_EOL)) { | |
throw new \FailureToWriteToFile($stream_path); | |
} | |
} | |
class FailureToWriteToFile extends Exception | |
{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Usage | |
* | |
* `php usage.php 1>log.txt 2>errors.txt` | |
* | |
* log.txt contains "sortie normale" | |
* errors.txt contains "vers erreur" | |
* | |
* --- | |
* | |
* `php usage.php > log.txt` | |
* | |
* log.txt contains "sortie normale" | |
* stderr messages are printed | |
*/ | |
require_once "stdLog.php"; | |
stdErr("vers erreur"); | |
stdOut("sortie normale"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better use core defined constants STDOUT and STDERR;