Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 025f55b308
Fetching contributors…

Cannot retrieve contributors at this time

executable file 61 lines (56 sloc) 1.388 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
<?php

/**
* Command line input from StdIn
*
* @author Craig Davis <craig.davis@learningstation.com>
*/
class IO {
  /**
* read a line from stdin
*
* echo "Enter your name: ";
* $name = IO::read();
* echo "Enter your age: ";
* $age = IO::read();
* echo "Hi $name, Isn't it Great to be $age years old?";
*
* @param int $length max length to fetch
*
* @return string stdin input
*/
  public static function read($length = 255) {
    if (!isset($GLOBALS['StdinPointer'])) {
      $GLOBALS['StdinPointer'] = fopen('php://stdin','r');
    }
    $line = fgets($GLOBALS['StdinPointer'], $length);
    return trim($line);
  }
  
  /**
* getOrQuit function
*
* @param string $prompt
* @param string $type [number|string]
*
* @return mixed value of prompt
*/
  public static function getOrQuit($prompt = "", $type = "string") {
    $value = null;
    
    echo $prompt, " (q to quit) ";
    
    while($value == null) {
      $value = IO::read();
      if ($value == 'q') {
        exit(0);
      }
      elseif (($type == "string") && !is_string($value)) {
        echo "- Please enter a string. (q to quit) \n";
        $value = null;
      }
      elseif (($type == "number") && !is_numeric($value)) {
        echo "- Please enter a number. (q to quit) \n";
        $value = null;
      }
    }
    return $value;
  }
}

/* End of file io.php */
Something went wrong with that request. Please try again.