What are the best practices for using PHP for command line scripts?
When using PHP for command line scripts, it is important to follow best practices to ensure efficiency and maintainability. This includes using the correct shebang line at the beginning of the script, handling command line arguments properly, using built-in functions like `fgets(STDIN)` for user input, and properly handling errors and exceptions.
#!/usr/bin/php
<?php
// Example of handling command line arguments
if ($argc < 2) {
echo "Usage: php script.php <argument>\n";
exit(1);
}
$argument = $argv[1];
echo "Argument passed: $argument\n";
// Example of reading user input from command line
echo "Enter your name: ";
$name = fgets(STDIN);
echo "Hello, $name";
// Example of handling errors and exceptions
try {
// Code that may throw an exception
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage() . "\n";
exit(1);
}