dtkp51520 2014-04-15 09:55
浏览 55
已采纳

将函数字符串参数转换为变量

I want to convert function string argument into array. so if I set 'user' than eventually in function I want to convert it to $user as soon as function start.

function

function get_item($object, $key)
{
    //I want to convert 'user' string in '$user' variable

    echo empty($object->$key) ? 'do_stuffs' : 'dont_do_stuffs';
}

usage

get_item('user', 'id');

I have tried something like

function get_item($object, $key)
{
    $$object = $object //this is not working

    echo empty($object->$key) ? 'do_stuffs' : 'dont_do_stuffs';
}
  • 写回答

1条回答 默认 最新

  • dongqing904999 2014-04-15 09:56
    关注

    Try the below:

    function get_item($object, $key) {
      // if there are no other code in this function, then `$$object` will not be defined.
      // you can't get $user from the outside the function scope.
      $value =  $$object->{$key};
      echo empty($value) ? 'do_stuffs' : 'dont_do_stuffs';
    }
    

    You are using variable variables, in most case, it's not a good idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料