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
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!
This will work:
php -r 'include "MyClass.php"; MyClass::foo();'
But I don't see any reasons do to that besides testing though.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With