将预定义变量作为函数参数传递
Passing predefined variables as function parameters
index.php:
require 'modulename.php';
$keyword = $_GET['q'];
getResults();
modulename.php:
$config = ... ;
$service = ... ;
function getResults($config, $service, $keyword) {
...
}
...但这会引发错误:
Missing argument 2 for getResults(), called in
index.php on line xx and defined in modulename.php
...似乎函数没有使用已经定义的变量,我如何让它使用那些?
您创建了需要三个参数才能调用的函数 getResults($config, $service, $keyword)
,但您调用它时没有使用任何参数。
你可以试试这个
在index.php
require 'modulename.php';
$keyword = $_GET['q'];
getResults($keyword );
modulename.php
function getResults($keyword = '') {
$config = ... ;
$service = ... ;
...
}
您的getResults();
需要参数
getResults($config, $service, $keyword);
如果您没有参数,则默认设置 false
getResults($config=false, $service=false, $keyword)
错误消息指出 arg 2 丢失 - 在您的函数中将引用 $keyword。在您提供的示例代码中,您同时定义了 $config 和 $service 但没有定义 $keyword - 因此,通过为函数参数提供默认值,您可以消除错误。然而,如果每个参数都是必需的,那么通过测试它们的值不是假的(这是它们在这个版本的函数中的默认值)那么函数将什么都不做。
或者,在调用函数之前定义每个变量:-
$config='';
$service='';
$keyword='';
function getResults($config=false, $service=false, $keyword=false) {
if( $config && $service && $keyword ){
...
}
}
index.php:
require 'modulename.php';
$keyword = $_GET['q'];
getResults();
modulename.php:
$config = ... ;
$service = ... ;
function getResults($config, $service, $keyword) {
...
}
...但这会引发错误:
Missing argument 2 for getResults(), called in index.php on line xx and defined in modulename.php
...似乎函数没有使用已经定义的变量,我如何让它使用那些?
您创建了需要三个参数才能调用的函数 getResults($config, $service, $keyword)
,但您调用它时没有使用任何参数。
你可以试试这个
在index.php
require 'modulename.php';
$keyword = $_GET['q'];
getResults($keyword );
modulename.php
function getResults($keyword = '') {
$config = ... ;
$service = ... ;
...
}
您的getResults();
需要参数
getResults($config, $service, $keyword);
如果您没有参数,则默认设置 false
getResults($config=false, $service=false, $keyword)
错误消息指出 arg 2 丢失 - 在您的函数中将引用 $keyword。在您提供的示例代码中,您同时定义了 $config 和 $service 但没有定义 $keyword - 因此,通过为函数参数提供默认值,您可以消除错误。然而,如果每个参数都是必需的,那么通过测试它们的值不是假的(这是它们在这个版本的函数中的默认值)那么函数将什么都不做。
或者,在调用函数之前定义每个变量:-
$config='';
$service='';
$keyword='';
function getResults($config=false, $service=false, $keyword=false) {
if( $config && $service && $keyword ){
...
}
}