How to call a PHP function from CLI?

十年热恋 提交于 2019-12-11 07:36:35

问题


Let's say I have a private function addUser() in function.php that takes $username as an input variable and does some stuff:

function addUser($username) {

//do some stuff

}

Now I want to call this function and pass the value $username, if possible with PHP CLI. I guess that won't work from outside function.php since it's private, but how could I do this then?


回答1:


php -r 'include("/absolute/path/to/function.php"); addUser("some user");'

This should work. Because you are basically executing all that code in between 's. And in that you can include function.php and, should appropriately call addUser().

see phpdoc.




回答2:


You get your command line argumenst passed in a argv array:

function addUser($username) {

//do some stuff

}

addUser( $argv[1] );



回答3:


You can use $argv. $argv[0] = the filename, $argv[1] = first thing after filename.

I.e. php function.php "some arg" would be addUser("some arg");




回答4:


function funcb()
{
    echo 'yes';
}

if (php_sapi_name() === 'cli') {
    if (count($argv) === 1) {
        echo 'See help command'.PHP_EOL;
        exit();
    }

    if (function_exists($argv[1])) {
        $func = $argv[1];
        array_shift($argv);
        array_shift($argv);
        $func(...$argv);
    }
}

This works for me!



来源:https://stackoverflow.com/questions/12814762/how-to-call-a-php-function-from-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!