문제

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';
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top