2

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?

JohnnyFromBF
  • 9,873
  • 10
  • 45
  • 59
  • I don't get the point with "_won't work from outside since it's private_". Can you explain what you mean? Basically the visibility of your class methods or functions has nothing to do with the context php is running in. – matthias Oct 10 '12 at 08:18

4 Answers4

5
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.

Prasanth
  • 5,230
  • 2
  • 29
  • 61
2

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

function addUser($username) {

//do some stuff

}

addUser( $argv[1] );
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • 2
    Why -1 ? SO should make it mandatory to write a comment when -1. – Riz Oct 10 '12 at 08:11
  • 1
    @JvdBerg only `argv` -> `$argv` – Havelock Oct 10 '12 at 08:13
  • @JvdBerg There are only a couple of recent downvotes on your profile, which really isn't something we consider abuse. If this continues, let us know. – NullUserException Oct 10 '12 at 08:17
  • I'd consider using PEAR Console_Commandline http://pear.php.net/package/Console_CommandLine :-) But plain ol' $argv sure works. – Jan. Oct 10 '12 at 08:43
  • @JvdBerg Thanks for the hint, I tried that with `php function.php john_doe` but now I get an error telling me `PHP Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION`. Seems as if the function can't handle the string john_doe, but that's weird. Do you have an idea why? – JohnnyFromBF Oct 10 '12 at 09:40
  • @JvdBerg It's this [here](http://code.google.com/p/piwik-ldap/source/browse/trunk/LoginLdap/Controller.php) with which I want to add LDAP Users to Piwik with a batch script. – JohnnyFromBF Oct 10 '12 at 10:34
0

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");

Steve
  • 2,936
  • 5
  • 27
  • 38
0
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!

Marcos Dantas
  • 836
  • 1
  • 11
  • 10