如何在函数中使用常量参数,而不必在调用时从其他函数传递它


How do I use a constant argument in a function and not have to pass it from other functions when called

我有一个函数,有3个参数,一个总是相同的,即数据库连接。

function threeArgs($one,$two,$dbh){
       // some code here
}

这是我想传递的常量参数

$dbh = new PDO(..............);

我正试图从另一个函数调用threeArgs()函数,但我只想传递2个参数而不是3个,例如:

threeArgs($one,$two);

我知道这一定很简单,或者我做得完全错了,但我不确定我需要搜索什么术语。

我把db连接放在一个函数中,然后从threeArgs()函数中调用它。例如,

function dbconnection(){
     $dbh = //connect to dataase
    return $dbh;
 }

这是我在threeArgs()中添加的内容。

function threeArgs($one, $two){
    dbconnection();
}

有更好的方法吗?

存储在global变量中:

$dbh = new POD();
function threeArgs ( $one, $two ) {
     global $dbh;
     // use  $dbh here...
}

如果您不喜欢使用global变量,您可以使用static变量来代替:

function threeArgs ( $one, $two ) {
     static $dbh = NULL;
     if ( ! $dbh ) $dbh = new POD();
     // use  $dbh here...
}