dpw63348 2014-05-17 11:21
浏览 52
已采纳

PHP从数组中提取值并将它们传递给函数

I'm trying to extract values from an array, and pass them to a function where they'll be used. I've used echo inside the function for this example.

I'm using extract to get all the values.

Thing is, this wont work. Do you see how this can be done?

<?php

$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more

$g = extract($my_array);

foo($g);

function foo($g) {
    echo 'My name is '.$a.', and I am '.$b;
}

?>
  • 写回答

2条回答 默认 最新

  • dsfhe34889789708 2014-05-17 11:25
    关注

    Functions in PHP have a different scope, so the variables $a, $b etc. aren't available inside your function. Trying to use them inside the function would result in Undefined variable notices (if you enable error reporting, that is).

    Right now, you're storing the return value of extract() (which is the total number of variables parsed) into your function. You want the values instead, so change your function like so:

    function foo($array) {
        extract($array);
        echo 'My name is '.$a.', and I am '.$b;
    }
    

    Note that I've moved the extract() call inside the function. This way, you wouldn't pollute the global scope with random variables (which may have undesired results and will make your debugging hard for no reason).

    Now you can call your function, like so:

    foo($my_array);
    

    Output:

    My name is Prince, and I am Funky
    

    Demo

    It's better to avoid extract() altogether, though. See: What is so wrong with extract()?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题