Code Lover
Code Lover

Reputation: 8348

Convert function string argument into variable

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

Upvotes: 0

Views: 342

Answers (1)

xdazz
xdazz

Reputation: 160833

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.

Upvotes: 1

Related Questions