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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答