PHP file.php arg1 arg2
Now I want to hardcode arg1
and arg2
into file.php
,how to do it?
PHP file.php arg1 arg2
Now I want to hardcode arg1
and arg2
into file.php
,how to do it?
I never tried it, but the arguments are contained in a certain array $argv
. So you have to set those entries if you want to hardcode them:
$argc = 3; // number of arguments + 1
$argv[0] = 'file.php'; // contains script name
$argv[1] = 'arg1';
$argv[2] = 'arg2';
$argv
is a reserved variable.
But note that the first two parameter that you specify via command line will always be overwritten by arg1
and arg2
.
Instead, if you need these values always in your script you should define them as normal variables at the top of your script:
$var1 = 'arg1';
$var2 = 'arg2';
or even as constants:
define('CONST1', 'arg1');
define('CONST2', 'arg2');
If you only want to provide arg1
, arg2
as parameter via the command line, then you can just access them via $argv[1]
and $argv[2]
, no need to mess with $argv
;
you would use argv() inside your php script to get the arguments
foreach ($argv as $args){
print $args."\n";
}
element 0 contains the script name. the rest are the arguments.
You want to test how many arguments to the function, then do something accordingly.
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);