I was reading through the documentation for PHP as I wanted to write a few console applications that would help me with some tasks that I wanted to be scripted. When it came time to gather input from the terminal I found that there were not that many choices available. In fact I could not find any tools using google that would fit my needs. Knowing that I wrote a small wrapper class that will get input from the terminal and explicitly cast it based on the the class function being used.
Here is the raw class:
/*
terminal input class
Anthony Wlodarski 2/15/2005
ant92083 at gmail dot com
*/
class terminal {
private $input;
function getLine()
{
$this->input = trim(fgets(STDIN));
return $this->input;
}
function getChar()
{
$this->input = trim(fgetc(STDIN));
return (string)$this->input;
}
function getInt()
{
return (int)$this->getLine();
}
function getString()
{
return (string)$this->getLine();
}
function getDouble()
{
return (double)$this->getLine();
}
}
So going from this class I have wrote a few tests for the class:
require_once('./terminal.php');
$PHPIN = new terminal();
// get a raw line from the terminal
echo "Enter a raw line: ";
$a = $PHPIN->getLine();
echo "Raw line from STDIN: $a\n\n";
var_dump($a);
// get a integer from the terminal
echo "Enter an integer: ";
$b = $PHPIN->getInt();
echo "Type(gettype): " . gettype($b) . " value: $b\n\n";
var_dump($b);
// get a string from the terminal
echo "Enter a string: ";
$c = $PHPIN->getString();
echo "Type(gettype): " . gettype($c) . " value: $c\n\n";
var_dump($c);
// get a float from the terminal
echo "Enter a float: ";
$d = $PHPIN->getDouble();
echo "Type(gettype): " . gettype($d) . " value: $d\n\n";
var_dump($d);
echo "Enter a single character: ";
$e = $PHPIN->getChar();
echo "Type(gettype): " . gettype($e) . " value: $e\n\n";
var_dump($e);So far it has worked like a charm. There are a couple of things I want to do and those are protection from invalid input as well as move it to a singleton setup. I don't think spawning many different copies of the same generic wrapper would be cost effect on the PHP interpreter.
0 Responses to PHP Terminal input.
Leave a Reply