PHP sprintf and scope


PHP sprintf and scope

为了更好的可读性/可维护性,我一直在重新安排一些代码,但遇到了一个我不太清楚的问题。

最初的代码基本如下:

$myFormat = '/* HTML structure */';
try {
    // SQL queries
    // Sorting and storing relevant data
    echo sprintf($myFormat,$1,$2...$N);
}
catch{
    // Error handling if there's a db issue
}

考虑到面向SQL的try/catch块中包含了大量不必要的内容,这一方法虽然有效,但组织得不太好。

所以我把它改成了:

$myFormat = '/* HTML structure */';
function dataHandling($a1,$a2...){
    // Sorting and storing relevant data
    echo sprintf($myFormat,$1,$2...$N);
}
try {
    // SQL queries
    dataHandling($s1,$s2...);
}
catch{
    // Error handling if there's a db issue
}

除了dataHandling内部的echo sprintf行外,其他一切似乎都正常工作,这是相当重要的。我只写了几天php,并认为这是一个范围问题,但我找不到任何解决类似问题的信息。

您需要将$myFormat作为参数传递。此外,sprintf的参数必须与函数参数相匹配。

function dataHandling($format, $a1,$a2...){
    // Sorting and storing relevant data
    echo sprintf($format,$a1,$a2...);
}
try {
    dataHandling($myFormat, $s1,$s2...);
}
catch{
    // Error handling if there's a db issue
}

在函数中使用全局关键字。

function dataHandling($a1, $a2 ...){
      global $myFormat;
      //remaining code
}

有关作用域的更多信息,请查看此项。