【问题标题】:How to return an Array's "name" as a String [duplicate]如何将数组的“名称”作为字符串返回 [重复]
【发布时间】:2016-12-28 21:06:20
【问题描述】:
$myAry = array();

// I want to return the array's name.

// something like
echo $myAry.name;

// Should print "$myAry".

谢谢,

【问题讨论】:

  • 老兄先学php基础或者看看教程
  • 当一个人甚至不知道这个人在做什么时,这是多么傲慢的评论!
  • 这篇文章解决了我的问题:stackoverflow.com/questions/255312/…

标签: php


【解决方案1】:

但如果您输入$myAry,您已经知道变量的名称。什么是 你想达到什么目标?

如果您绝对必须知道变量的身份...

function my_function ($my_array) {
    $caller_info = array_shift(debug_backtrace());
    $lines = file($caller_info['file']);
    $line = $lines[$caller_info['line'] - 1];
    if(preg_match('/my_function\\s*\\(\$(\\w+)/', $line, $matches)) {
        $name_of_my_array = $matches[1];
        echo $name_of_my_array;
    }

}

这是你想要的吗?

【讨论】:

  • 谢谢,这很接近,但它每次只返回 my_function 的 arg 名称(例如 $my_array),无论传递什么数组,而不是 arg 指的是什么。示例:如果我像这样使用它 my_function($new_name) 它应该返回一个字符串 "$new_name" 而不是每次都返回的 "$my_array"。
【解决方案2】:

$array = array('name12'); $comma_separated = implode(",", $array);

回显 $comma_separated; // name12

// 使用空数组时为空字符串:

var_dump(implode('hello', array())); // string(0) ""

【讨论】:

  • 不寻找元素。
【解决方案3】:

你可以像这样得到参数​​名称:

function get_function ($my_array) {
    $f = new ReflectionFunction($my_array);
    $result = array();
    foreach ($f->getParameters() as $param) {
        $result[] = $param->name;   
    }
    return $result;

}

function sayHello($helloWorlds){
    echo $helloWorld;
}

print_r(get_function('sayHello'));;


 //Output
 Array ( [0] => helloWorlds ) 

【讨论】:

  • 不寻找元素。
  • @SpaceCorpSolutions 为您的问题找到解决方案,请检查。
猜你喜欢
  • 2013-12-31
  • 1970-01-01
  • 2014-03-28
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多