簡體   English   中英

php-CLI和自定義命令

[英]php - CLI and custom commands

我目前正在嘗試制作一個可以通過執行命令與用戶交互的php腳本。 用戶必須在終端中使用腳本。

這是我所談論的例子:

>php robot.php
>Hello, I'm the GoodRobot number 8731039139, nice to meet you!
>Please type a command below:
>say "Hello" **// user types this**
>GoodRobot no 8731039139: Hello **// robot.php outputs this**

我希望它在調用init()時立即使其具有交互性,但是我一直在嘗試做您在下面可以看到的內容,並且它似乎不起作用。

這是我的完整代碼

<?php

class Robot 
{
    // ?? \\
}

class GoodRobot extends Robot
{
    static protected $serialNumber; 

    private $name;
    private $type = "Droid";

    public function __construct($name)
    {
        $this->name = $name;
        echo "Hello, I'm the GoodRobot number " . self::$serialNumber . ", nice to meet you!\n";
    }

    public function init()
    {
        echo "Please type a command below:" . PHP_EOL;
        $handle = fopen ("php://stdin","r");
        $line = fgets($handle);
        if(trim($line) != 'say')
        {
            print(say($str));
        }
        elseif (trim($line) != 'help') {
            print(help());
        }
        else
        {
            echo "ERROR: Unknown command. Type \"help\" if you need help." . PHP_EOL;
        }
    }

    public function setName($name) 
    {
        $this->name = $name;
    }

    public function getName($name)
    {
        return $this->name;
    }

    public function help()
    {
        echo "Here is a list of commands: \n - say \"something\" \n - shutDown \n";
    }

    public function say($str)
    {
        echo "GoodRobot no " . self::$serialNumber . " : " . $str . "\n";
    }

    public function turnOn()
    {
        echo "Waking up... Please be patient.\n";
        parent::__construct();
    }

    public function shutDown()
    {
        echo "Shutting down...\n";
        exit;
    }
}

$hi = new GoodRobot("hi");
$hi -> init();

當我試圖“說”時

顯示致命錯誤

PHP致命錯誤:未捕獲錯誤:調用未定義的函數say()

引用當前類中的方法時,需要使用$this-> 我還將您的輸入更改為readline()因為它可以處理IO。

還要注意字符串操作,以更改say "Hello"以刪除第一位和所有引號。

public function init()
{
    echo "Please type a command below:" . PHP_EOL;
    $line = readline();
    if(substr($line, 0, 3) == 'say')
    {
        $line = substr($line, 3);
        $line = rtrim(trim($line,"\" "),"\" \n\r");
        $this->say($line);
    }
    elseif (substr($line, 0, 4) == 'help') {
        $this->help();
    }
    else
    {
        echo "ERROR: Unknown command. Type \"help\" if you need help." . PHP_EOL;
    }
}

我不確定為什么要在say()調用周圍使用print()say()回顯字符串,因此不需要打印。

您還需要檢查前三個字符是否為'say',而不是使用trim() 與“幫助”相同(盡管這次為4個字符)。

更新:測試時添加

ini_set('display_errors', 'On');
error_reporting(E_ALL);

在腳本頂部,它有助於顯示代碼中的任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM