2

I'm creating a website and somewhere in the code I need to query for a user attribute (ex:account state) and in the same row I have the reason, case is account state is "suspended".

I'm trying to minimize the requests to the database, so I created a function to verify account state.

function getAccountState($userid,$reason){}

What I am trying to do is if account state is "suspended" I would change the $reason to "the database reason".

I've already done that but if I change the $reason inside the function, outside the function it will not change. I searched for "php pointers" on google but I think there is not such thing.

Is there a way to do this? Other way I'll just make another database request...

1
  • PHP doesn't have pointers or dynamic memory. Even references aren't exactly like references you'd see in C++ (although they're used pretty much the same way). Commented Feb 19, 2013 at 17:12

4 Answers 4

2

You could of course pass the variable by reference but as you don't seem to need it, I would just return it from the function:

function getAccountState($userid){
  // your code
  return $reason;
}

and call it like:

$reason = getAccountState($userid);

If you want to stay your code as it is now, you could pass the variable by reference:

function getAccountState($userid,&$reason){}
                                 ^ like so
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I was returning the "state" attribute, so the first way is not the one i'm looking. The second one was perfect. Thanks for the fast response !
@Ricardo Neves You could return an array or just use the second solution :-)
0

You could consider passing it in by reference. Or perhaps just changing the function to return the correct information.

Comments

0

In the definition of functions you can tell that $reason argument is passed by reference, not value. To do so, use & in front of variable:

function getAccountState($userid,& $reason){}

Comments

0

You are looking for references, in PHP terminology, not pointers.

They work this way :

function getAccountState($userid, &$reason){  // Notice the &
    $reason = "database locked";  // Use it as a regular variable
}


getAccountState(12345, $reason);  // Here, it is written as a regular variable, but it is a ref.
echo $reason;   // echoes "database locked"

Comments

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.