php 如何从命令行执行类中的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4969735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:23:37  来源:igfitidea点击:

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

phpcommand-line

提问by dan.codes

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 docs. I know how to run a file, obviously php -fbut not sure how to run that file which is a class and execute a given method

基本上我有一个 PHP 类,我想从命令行测试它并运行某个方法。我确定这是一个基本问题,但我从文档中遗漏了一些东西。我知道如何运行文件,显然php -f但不知道如何运行作为类的文件并执行给定的方法

回答by netcoder

This will work:

这将起作用:

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

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

但我认为除了测试之外没有任何理由这样做。

回答by J.C. Inacio

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

我可能会使用 call_user_func 来避免对类或方法名称进行硬编码。输入可能应该使用某种验证,但......

<?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

回答by Sander Marechal

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

这是 Repox 代码的一个更简洁的示例。这只会在从命令行调用时运行 de 方法。

<?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();
}

?>

回答by Repox

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.

正如 Pekka 已经提到的,您需要编写一个脚本来处理特定方法的执行,然后从命令行运行它。

test.php:

测试.php:

<?php
class MyClass
{
  public function hello()
  {
    return "world";
  }
}

$obj = new MyClass();
echo $obj->hello();
?>

And in your commandline

在你的命令行中

php -f test.php