Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 515
dan.codes Avatar asked Feb 11 '11 13:02

dan.codes


People also ask

How do I run a Python class from the command line?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

This will work:

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

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

like image 96
netcoder Avatar answered Oct 13 '22 18:10

netcoder


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 
like image 34
J.C. Inacio Avatar answered Oct 13 '22 17:10

J.C. Inacio