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?

1
  • 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. Commented Oct 10, 2012 at 8:18

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

function addUser($username) {

//do some stuff

}

addUser( $argv[1] );

6 Comments

Why -1 ? SO should make it mandatory to write a comment when -1.
@JvdBerg only argv -> $argv
@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.
I'd consider using PEAR Console_Commandline pear.php.net/package/Console_CommandLine :-) But plain ol' $argv sure works.
@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?
|
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");

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.