存储和访问函数中的代码片段

时间:2009-06-04 19:14:28

标签: php

在我的包含文件夹中,我有一个功能...

function storelistingUno() {

$itemnum=mysql_real_escape_string($_POST['itemnum']);
$msrp=mysql_real_escape_string($_POST['msrp']);
$edprice=mysql_real_escape_string($_POST['edprice']); //This value has to be the same as in the HTML form file
$itemtype=mysql_real_escape_string($_POST['itemtype']);
$box=mysql_real_escape_string($_POST['box']);
$box2=mysql_real_escape_string($_POST['box2']);
$box25=mysql_real_escape_string($_POST['box25']);
$box3=mysql_real_escape_string($_POST['box3']);
$box4=mysql_real_escape_string($_POST['box4']);
$box5=mysql_real_escape_string($_POST['box5']);
$box6=mysql_real_escape_string($_POST['box6']);
$box7=mysql_real_escape_string($_POST['box7']);
$box8=mysql_real_escape_string($_POST['box8']);
$itemcolor=mysql_real_escape_string($_POST['itemcolor']);
$link=mysql_real_escape_string($_POST['link']);
$test = "yes!";

}

我在大约8页中引用了这一点,并且我认为从中创建一个函数会更容易,并且从现在开始只触摸它。所以我在我的代码中引用了storelistingUno();,但我认为它不起作用,因为我试图执行echo $test;并且没有任何反应。我需要退货吗?

感谢。

4 个答案:

答案 0 :(得分:1)

$ test是该函数中的局部变量 - 您需要将其设置为全局变量(将global $test;放在函数的开头或使用$GLOBALS['test']而不是$test或返回值。

您是否考虑使用该功能来逃避价值?也许你可以让它执行查询,然后你就不必返回/使用全局变量。

编辑: 另一种方法是包含代码而不是使用函数 - 不推荐使用...

答案 1 :(得分:1)

查看extract()。你可以这样做:

<?php

function getEscapedArray()
{
  $keys = array('itemnum', 'msrp', 'edprice', 'itemtype', 'box', 'box2', 'box25', 'box3', 'box4', 'box5', 'box6', 'box7', 'box8', 'itemcolor', 'link');

  $returnValues = array();
  foreach ($keys as $key) {
    $returnValues[$key] = mysql_real_escape_string($_POST[$key]);
  }

  $returnValues['test'] = 'yes!';

  return $returnValues;

}

extract(getEscapedArray());
echo $test;

虽然 - 它仍然不是最好的方法。最好的方法是使用该函数的返回值作为数组。

$parsedVals = getEscapedArray();
echo $parsedVals["test"];

答案 2 :(得分:1)

如果你绝对需要这些变量全局

function storelistingUno()
{
    $desiredGlobals = array( 
         'itemnum'
        ,'msrp'
        ,'edprice'
        ,'itemtype'
        ,'box'
        ,'box2'
        ,'box25'
        ,'box3'
        ,'box4'
        ,'box5'
        ,'box6'
        ,'box7'
        ,'box8'
        ,'itemcolor'
        ,'link'
    );
    foreach ( $desiredGlobals as $globalName )
    {
        if ( isset( $_POST[$globalName] ) )
        {
            $GLOBALS[$globalName] = mysql_real_escape_string( $_POST[$globalName] );
        }
    }
}

答案 3 :(得分:0)

在开始在函数中编辑它们之前,你必须将每个变量标记为全局变量...这不是推荐的,因为它的编码风格很差,但它可能对你有帮助

$test = '';
function foo() {
    global $test;
    $test = 'bar';
}
echo $test; //prints nothing
foo();
echo $test; // prints "bar"