JC Dev JC Dev - 4 months ago 9
PHP Question

PHP: cannot pass parameters to a function in another file

I have

file1.php
which gets data and want to return to the client-side. It loads another php file in at the top of itself:
require_once '/utils/file2.php';


The function
returnJson()
is in the
file2.php
as below:

function returnJson( $param1, $param2 ) {
$res = [
'timestamp' => time()
];
if ( isset( $param1 ) ) $res['param1'] = $param1;
if ( isset( $param2 ) ) $res['param2'] = $param2;
echo json_encode( $res );
exit;
}


At the end of
file1.php
it calls
returnJson( $param1, $param2 )
. The
$param1
and
$param2
both have values.

Then on the client-side I have the json result only with the
timestamp
but missing the other two parameters.

{
"timestamp": 1470271525
}


So I change the
returnJson
function to add the parameters in
$res
without checking:

function returnJson( $param1, $param2 ) {
$res = [
'timestamp' => time(),
'param1' => $param1,
'param2' => $param2
];
echo json_encode( $res );
exit;
}


Then on the client-side I got json like this:

{
"timestamp": 1470271525,
"param1": null,
"param2": null
}

Answer

It means that the value of one or both parameters you're passing to the function, e.g. returnJson($var1, $var2), is null, not that you're not passing them. var_dump() the variables before your function call, and die() to see what values they are. Then check for typos, follow their code path back to where they're set, etc.