场景/问题隔离
:假设我的程序使用多个变量。在程序开始时,我希望通过一个代码很少的通用函数同时操作许多变量,然后在流程的后面,在特定函数中只使用一些独特的变量。
问题
:如何通过引用foreach循环传递多个变量?或者是否有更好的/可选的方法来循环使用多个确定的变量?
与主题相关的帖子
但没有解决我的问题:
背景(相关人员):
我有一个使用getopts的命令行程序
http://hash-bang.net/2008/12/missing-php-functions-getopts/
为了得到各种各样的参数,我得到了大约20个变量。我想运行所有变量,这些变量包含文件路径(大约10个),一次通过“常规”函数reduceHierarchyDots()(而不是调用函数10次)。
/// The "general" function:
function reduceHierarchyDots ($file) {
while (preg_match('|./\.{2}/|', $file)) { $file = preg_replace('|/([^/]+)/\.{2}/|', '/', $file, 1); }
$file = preg_replace('|(/(\./)+)|', '/', $file);
$file = preg_replace('|^(\./)+|', '', $file);
return $file;
}
function reduceHierarchyDotsRef (&$file) {
while (preg_match('|./\.{2}/|', $file)) { $file = preg_replace('|/([^/]+)/\.{2}/|', '/', $file, 1); }
$file = preg_replace('|(/(\./)+)|', '/', $file);
$file = preg_replace('|^(\./)+|', '', $file);
}
/// The "many" variables:
$x = "something";
$y = 123;
$y = array ("a", "B", 3);
$a = "/Users/jondoe/Desktop/source/0.txt";
$b = "/Users/jondoe/Desktop/source/../1.txt";
$c = "/Users/jondoe/Desktop/source/../../2.txt";
$arrOne = array (
"v1" => "/some/thing/../1.pdf",
"v2" => "/some/thing/../../2.pdf",
"v3" => "/some/thing/../../../3.pdf"
);
$arrTwo = array (
"./1.doc",
"/so.me/.thing/ends./././2.doc",
"./././3.doc"
);
/// At the beginning I want to run multiple determined variables through a "general" function:
/// Debugging: Variables BEFORE the manipulation:
echo("BEFORE:\n"); var_dump($b, $arrOne["v2"], $arrTwo[2]); echo("\n");
/// Method works, but is long! (1 line/statement per function call)
reduceHierarchyDotsRef($b);
reduceHierarchyDotsRef($arrOne["v2"]);
reduceHierarchyDotsRef($arrTwo[2]);
/// Hence, I'd like to pass all variables by reference at once to a foreach loop:
These cause: Parse error: syntax error, unexpected '&':
// foreach ( array($b, $arrOne["v2"], $arrTwo[2] ) as &$file) { $file = reduceHierarchyDots($file); }
// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as &$file) { $file = reduceHierarchyDotsRef($file); }
These have no effect on the intended variables:
// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as $file) { $file = reduceHierarchyDots($file); }
// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as $file) { $file = reduceHierarchyDotsRef($file); }
/// Debugging: Variables AFTER the manipulation:
echo("AFTER:\n"); var_dump($b, $arrOne["v2"], $arrTwo[2]);
/// After the "general" function ran over various variables, the more specific actions happen: ...
?>