我正在构建一个控制台应用程序,并希望使用已经编写的代码而不对其进行修改。但是,我需要命令的输出。是否可以做这样的事情:
function func() {
/* Let's say this function contains already written
code and it would be easier to rewrite it than modify */
echo 'Confirm action';
$input = fgets(fopen('php://stdin', 'r'));
if ($input == 'y') echo 'okay';
else echo 'no';
return 0;
}
$code = func();
// func() returns non zero only on error and confirming/declining an action returns 0.
// I want to know if the action was confirmed.
// Using ob_start() prevents echo from working in the function,
// i.e. the user sees a blank screen waiting for input.
这可能吗?
我正在用 Yii 框架写这个。任何想法都值得赞赏。
用 popen 解决了这个问题,例如:
$handle = popen('php yiic migrate create '.$name, 'r');
$output = '';
while (!feof($handle))
{
$read = fread($handle, 2096);
$output .= $read;
echo $read;
}
$exitCode = pclose($handle);