Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function in a PHP script from the command line

I have a script that has a bunch of different parameterized functions. Is it possible to call any of these functions from the command line and pass in the arguments instead of me having to hard code the function calls in the script?

F.Y.I: I do know how to execute a simple PHP script from the command line

doesn't quite call the function, remember script.php has around 5 different functions and I am looking to call only 1, is that possible

like image 709
user1020069 Avatar asked Sep 18 '12 17:09

user1020069


People also ask

How do you call a function in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used.

Can you execute PHP script from the command line?

A PHP script can be executed from the command line even without having any web server software installed. To run the PHP script from the command line you should just have a PHP CLI (PHP Command Line Interface) installed on your system.

How do I run a PHP script from the command line with arguments?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

What is PHP CLI command?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


1 Answers

No, you cannot do that directly. You have a few options:

  • Put every function in a separate php file and call the php file
  • use the first argument passed to the php file as the function name, and write a few lines of code to select the correct function.

Update:

Here is a example of using the first passed parameter as a function call:

if(function_exists( $argv[1] ))
  call_user_func_array($argv[1], $argv);
like image 95
JvdBerg Avatar answered Nov 07 '22 19:11

JvdBerg