dan.codes
dan.codes

Reputation: 3523

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

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

Upvotes: 25

Views: 51270

Answers (4)

Repox
Repox

Reputation: 15476

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

Upvotes: 6

Sander Marechal
Sander Marechal

Reputation: 23216

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

?>

Upvotes: 7

J.C. Inacio
J.C. Inacio

Reputation: 4472

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

Upvotes: 14

netcoder
netcoder

Reputation: 67695

This will work:

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

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

Upvotes: 47

Related Questions