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

时间:2014-04-15 09:55:42

标签: php arguments

我想将函数字符串参数转换为数组。所以如果我设置'user'而不是最终在函数中,我想在函数启动后立即将其转换为$user

功能

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

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

使用

get_item('user', 'id');

我尝试了类似

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

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

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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';
}

您使用的是变量变量,在大多数情况下,这不是一个好主意。

相关问题