25

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

dan.codes
  • 3,523
  • 9
  • 45
  • 59

4 Answers4

46

This will work:

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

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

netcoder
  • 66,435
  • 19
  • 125
  • 142
  • 3
    That's the most awesome trick I found for command line since I started looking for it :) – Damodar Bashyal Jun 05 '14 at 02:10
  • I found I can't use this method of I'm making use of the $this keyword for variables I've defined as attributes. (e.g. `public function __construct(){ $this->foo = bar;} public function stuff(){ echo $this->foo;}`) If I try to call the class method `MyClass::stuff()`, then I would get an error. – VinceOmega Sep 16 '14 at 20:43
  • @VinceOmega - because you're statically calling the method (bypassing the constructor) and cannot access non-static properties. – HorusKol Nov 12 '15 at 02:32
14

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
J.C. Inacio
  • 4,442
  • 2
  • 22
  • 25
7

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

?>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sander Marechal
  • 22,978
  • 13
  • 65
  • 96
6

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
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Repox
  • 15,015
  • 8
  • 54
  • 79