从php函数内部返回数组不起作用

时间:2013-05-01 08:18:27

标签: php

我试图将$ keysList数组从函数中取出,但似乎在某处出错了。我收到了错误:

Passed Notice: Uninitialized string offset: 2 in C:\web\apache\htdocs\dev\case2.php on line 40 Notice: Uninitialized string offset: 1 in C:\web\apache\htdocs\dev\case2.php on line 40 Notice: Uninitialized string offset: 0 in C:\web\apache\htdocs\dev\case2.php on line 40 Output = a , a and a .

如何做到这一点?

<?php

$catHandle = "addCat";

function validCatKeys($catHandle,$keysList)
{

    switch($catHandle){

    case "addCat":

            $listCountryCode = 'US';
            $listUserName    = 'Norman';
            $listUserId      = '1';
            $keysList        = array($listCountryCode,$listUserName,$listUserId);
            return true;
        break;

    case "addSubCat":

        break;

    case "addElm":

        break;

    default:
       return false;
    }


}



if(validCatKeys($catHandle,$keysList = ''))
{

    echo 'Passed';
    list($a, $b, $c) = $keysList;
    echo "Output =  a $a, a $b and a $c.";

}else{echo 'Failed';
}



?>

3 个答案:

答案 0 :(得分:1)

function validCatKeys($catHandle,$keysList)
{

    switch($catHandle){

    case "addCat":

            $listCountryCode = 'US';
            $listUserName    = 'Norman';
            $listUserId      = '1';
            $keysList        = array($listCountryCode,$listUserName,$listUserId);
            return $keysList;
        break;
    ....

答案 1 :(得分:1)

请在下面的代码中尝试其工作演示http://codepad.viper-7.com/2Eyym1 数组$keyList是局部变量并具有局部范围,因此声明它global它将起作用。

<?php
    $catHandle = "addCat";

    function validCatKeys($catHandle,$keysList)
    {
        global $keysList;

        switch($catHandle){

        case "addCat":

                $listCountryCode = 'US';
                $listUserName    = 'Norman';
                $listUserId      = '1';
                $keysList        = array($listCountryCode,$listUserName,$listUserId);
                return true;
            break;

        case "addSubCat":

            break;

        case "addElm":

            break;

        default:
           return false;
        }


    }



    if(validCatKeys($catHandle,$keysList = array()))
    {

        echo 'Passed';
        list($a, $b, $c) = $keysList;
        echo "Output =  a $a, a $b and a $c.";

    }else{echo 'Failed';
    }

答案 2 :(得分:1)

在函数定义中定义引用传递的$keysList变量:

function validCatKeys($catHandle,&$keysList)

(注意&

这将使$keysList变量的任何内部更改在函数外部可用。