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

Php 将函数字符串参数转换为变量,php,arguments,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');

我想把函数字符串参数转换成数组。所以,如果我最终在函数中设置了
'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';
}
请尝试以下方法:

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

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

@JatinSoni请看我的评论。我明白了。实际上,我试图从函数外部获取一个对象。那么这意味着它将不起作用?但当我传递变量本身
$user
时,它在没有任何error@JatinSoni是的,您必须将其传递给函数,或者使用全局变量(强烈建议不要这样做)