PHP CLI自定义命令开发:实现交互式终端脚本的问题
Got it, let's tackle this terminal-interactive PHP robot script issue. You want the script to jump straight into interactive mode right after calling init(), so here's a solid implementation that should work as you expect, along with explanations for each part.
Solution: Interactive PHP Terminal Robot Script
First, let's build a clean, class-based structure that handles initialization and interactive input seamlessly.
Full Working Code Example
<?php class GoodRobot { private $robotId; public function init() { // Set up the robot's unique ID (you could generate this dynamically too) $this->robotId = '8731039139'; // Greet the user immediately after initialization echo "Hello, I'm the GoodRobot number {$this->robotId}, nice to meet you!\n"; // Launch interactive mode right away $this->startInteractiveLoop(); } private function startInteractiveLoop() { while (true) { echo "Please type a command below:\n"; // Read raw input from the terminal $userInput = trim(fgets(STDIN)); // Add an exit command for graceful termination if (strtolower($userInput) === 'exit') { echo "Goodbye!\n"; exit; } // Parse and handle the "say" command format you specified if (preg_match('/^say "(.*)"$/', $userInput, $matches)) { $message = $matches[1]; echo "GoodRobot no {$this->robotId}: {$message}\n"; } else { echo "Sorry, I don't get that. Try using the format: say \"your message here\"\n"; } } } } // Initialize and start the robot $robot = new GoodRobot(); $robot->init(); ?>
Key Parts Breakdown
init()Method: This handles robot setup (like assigning the ID) and immediately triggers the interactive loop—exactly the behavior you're after.- Terminal Input Handling:
fgets(STDIN)reads a line of input from the terminal, andtrim()cleans up extra newlines or whitespace that might mess with command parsing. - Command Parsing: The regex
/^say "(.*)"$/specifically matches the "say" command format you provided, capturing the message inside the quotes to echo back. - Continuous Loop: The
while(true)loop keeps the script running until the user typesexit, so the robot stays responsive to multiple commands.
Testing the Script
Run it in your terminal like this:
php robot.php
You’ll see the greeting prompt, then can type say "Hello" to get the exact response from your example.
Troubleshooting Common Issues
If you ran into problems earlier, here are a few likely fixes:
- Input Reading Errors: Make sure you're using
STDINfor terminal input—$_POST/$_GETonly work for web-based scripts, not terminal ones. - Loop Not Triggering: Double-check that
init()actually callsstartInteractiveLoop(); typos or incorrect method scope (like marking itprivatebut trying to call it externally) can block this. - Command Recognition Failures: If the robot doesn't pick up the "say" command, verify your regex—quoted strings need proper escaping, and the pattern has to match the exact input format.
内容的提问来源于stack exchange,提问作者Margaret Osborn
相关产品推荐
相关产品推荐

