Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a PHP function from the command line

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.

like image 855
Jack Smit Avatar asked Dec 07 '12 11:12

Jack Smit


People also ask

How do you call a PHP function?

In PHP, a function is declared with the function keyword prefixed with the function name and the calling of a function in a program is done by just calling the name of the function wherever required.

Can we use PHP for command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

Can I call function in function PHP?

So as long as you have your function defined when you hit a certain spot in your code it works fine, no matter if it's called from within another function. Show activity on this post. If you define function within another function, it can be accessed directly, but after calling parent function.


2 Answers

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.

like image 151
Tim S. Avatar answered Oct 10 '22 02:10

Tim S.


Use

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

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

like image 38
user7282 Avatar answered Oct 10 '22 03:10

user7282