0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@JatinSoni See my comment.
I see. Actually I am trying to get an object from outside the function. So this means it will not work? but when I passed variable itself $user it is working without any error
@JatinSoni Yes, you have to pass it to the function, or using global variable (which is strongly not recommended.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.