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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This will work:
php -r 'include "MyClass.php"; MyClass::foo();'
But I don't see any reasons do to that besides testing though.
回答2:
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
回答3:
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();
}
?>
回答4:
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