How do you execute a method in a class from the command line

前端 未结 4 1559
感情败类
感情败类 2020-12-09 03:41

Basically I have a PHP class that that I want to test from the commandline and run a certain method. I am sure this is a basic question, but I am missing something from the

相关标签:
4条回答
  • 2020-12-09 03:54

    I would probably use call_user_func to avoid harcoding class or method names. Input should probably use some kinf of validation, though...

    <?php
    
    class MyClass
    {
        public function Sum($a, $b)
        {
            $sum = $a+$b;
            echo "Sum($a, $b) = $sum";
        }
    }
    
    
    // position [0] is the script's file name
    array_shift(&$argv);
    $className = array_shift(&$argv);
    $funcName = array_shift(&$argv);
    
    echo "Calling '$className::$funcName'...\n";
    
    call_user_func_array(array($className, $funcName), $argv);
    
    ?>
    

    Result:

    E:\>php testClass.php MyClass Sum 2 3
    Calling 'MyClass::Sum'...
    Sum(2, 3) = 5
    
    0 讨论(0)
  • 2020-12-09 04:01

    As Pekka already mentioned, you need to write a script that handles the execution of the specific method and then run it from your commandline.

    test.php:

    <?php
    class MyClass
    {
      public function hello()
      {
        return "world";
      }
    }
    
    $obj = new MyClass();
    echo $obj->hello();
    ?>
    

    And in your commandline

    php -f test.php
    
    0 讨论(0)
  • 2020-12-09 04:02

    This will work:

    php -r 'include "MyClass.php"; MyClass::foo();'
    

    But I don't see any reasons do to that besides testing though.

    0 讨论(0)
  • 2020-12-09 04:20

    Here's a neater example of Repox's code. This will only run de method when called from the commandline.

    <?php
    class MyClass
    {
      public function hello()
      {
        return "world";
      }
    }
    
    // Only run this when executed on the commandline
    if (php_sapi_name() == 'cli') {
        $obj = new MyClass();
        echo $obj->hello();
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题