【问题标题】:How to create switch() via array without if-else? [duplicate]如何在没有 if-else 的情况下通过数组创建 switch()? [复制]
【发布时间】:2015-04-18 14:44:59
【问题描述】:

我有两个功能,想在$test=onefunction1() 运行时和$test=twofunction2() 运行时运行。像这样:

switch ($test)
 {

case "one":
function1();
break;

case "two":
function2();
break;

 }

现在如何通过数组(选择)?有人知道吗?

如何在函数上设置数组的键?像这样:

array("one"=>function1(),"two"=>function2());

【问题讨论】:

  • 请添加一个示例然后你想如何使用它!
  • 我想要:当 $test=one 时回显“one”,当 $test=two 时回显“two”。使用数组 php
  • 不,回显'test'字符串,或者运行一个函数。
  • 完全不清楚你在这里要求什么?
  • @halfer tnx 进行编辑。

标签: php


【解决方案1】:
<?php
function func1()
{
    print "111\n";
}

function func2()
{
    print "222\n";
}

//put functions names into an array
$functions = array(
    'one' => "func1",
    'two' => "func2",
);

$test = 'two';

if(isset($functions[$test]))
{
    call_user_func($functions[$test]);
}

输出:

222

http://php.net/manual/en/function.call-user-func.php

【讨论】:

  • 您的解决方案很棒,但我不想要任何 if 和类似 call_user_func(); 的功能。无论如何 tnx 培训call_user_func(); 给我。 :)
  • 你能告诉我哪个更好吗? call_user_func($functions[$test]);$functions[$test]();
  • @Fatemeh 实际上是一样的——php 必须在其函数表中搜索具有适当名称的函数。区别仅在于语法。
【解决方案2】:

user4035的答案是正确的,但换句话说我们可以使用:

$arr[$test]();

改为

call_user_func($arr[$test]);

然后:(完整代码):

  function func1(){
    echo 'func1 runing';
        }

  function func2(){
    echo 'func2 runing';
        }

     $test='one';

     $arr=array ('one'=>'func1','two'=>'func2');
     $arr[$test]();

输出:

func1 runing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多