How do you execute a method in a class from the co

2019-01-23 03:43发布

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 -f but not sure how to run that file which is a class and execute a given method

4条回答
太酷不给撩
2楼-- · 2019-01-23 04:19

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

?>
查看更多
做自己的国王
3楼-- · 2019-01-23 04:20

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
查看更多
Bombasti
4楼-- · 2019-01-23 04:36

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
查看更多
Melony?
5楼-- · 2019-01-23 04:39

This will work:

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

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

查看更多
登录 后发表回答