Call a PHP function from the command line

给你一囗甜甜゛ 提交于 2019-12-18 11:41:10

问题


I have a file called address.php with a few functions in it. I want to call a specific function in that file from the command line. How?

The name of the function is called exportAddress and that function expects a single parameter.


回答1:


By using the -r parameter you can run a script in-line.

php -r "require 'address.php'; exportAddress(12345);"

There are no other options. A function in PHP can only be called by a PHP script.




回答2:


php -r 'include "/var/www/test/address.php";exportAddress(1);'

where "/var/www/test/arr.php" is file name including path and exportAddress() is function inside that file




回答3:


Add this to the top of the file "/var/www/test/address.php"...

foreach ($argv as $i=>$arg )
{
    if ( $arg == "exportAddress" )
    { 
        exportAddress($argv[$i+1]);
    }
}

then from the command line execute#> php /var/www/test/address.php exportAddress 12345




回答4:


you can make your file "somefile.php" organized as follows:

function func1(){....}
function func2(){....}
function func3(){....}
....
foreach ($argv AS $arg){
    function_exists($arg) AND call_user_func($arg);
}

Then from command line or Linux cronjob, you run the following command

php /path/to/somefile.php arg1 arg2 arg3 ...


来源:https://stackoverflow.com/questions/13761915/call-a-php-function-from-the-command-line

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