468,117 Members | 1,452 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,117 developers. It's quick & easy.

How does "return" work in a function?

38 32bit
I have a situation where i've used a session variable to store a user's custom session privilege to be used to determine which version of a table to show based on the user's predefined privilege. (a one character VARCHAR string which is set to 0, 1, or 2 in the SQL table where 0 means banned, 1 means regular user, and 2 means app administrator). Can I declare in a function "return priv" and use it like the following, or does "return" work differently in a function?

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. function privcheck() {
  4.  $priv = $_SESSION['priv'] ;
  5.  return $priv;
  6. }
  7.  
  8. if ( privcheck()=== 0) {
  9. echo 'do code for case 0';
  10. }
  11.  
  12. if ( privcheck() ===1) {
  13. echo 'do code for case 1';
  14. }
  15.  
  16. if ( privcheck() ===2) {
  17. echo 'do code for case 2';
  18. }
  19.  
  20. exit;
  21. ?>
  22.  
Mar 1 '21 #1
2 1624
AjayGohil
84 64KB
Hello

firstly you have to assign value $priv and you can use == instead of === because of === check value with their datatype.

For more information you can refer following:
https://www.w3schools.com/php/keywor...from%20running.
https://www.tutorialspoint.com/php/php_functions.htm
Mar 3 '21 #2
bakertaylor28
38 32bit
Which, from my understanding, is what the return is for in the function:
Expand|Select|Wrap|Line Numbers
  1.  function privcheck() {
  2. $priv = $_SESSION['priv'];
  3.  return $priv;
  4. }
  5.  
So That, within the If statement the following become more or less equivalent:

Expand|Select|Wrap|Line Numbers
  1. if ( $priv === foo) {
  2.  
  3. }
  4.  
Expand|Select|Wrap|Line Numbers
  1. if ( privcheck() === foo) {
  2.  
  3. }
  4.  
Also, using === instead of == prevents code injection, because of the fact that (in this case) SQL returns the value as a string, not an integer. This in turn prevents exploitative code injection by using an unexpected datatype, and then requiring that datatype.
Mar 3 '21 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by wenmang | last post: by
3 posts views Thread by timmy_dale12 | last post: by
15 posts views Thread by Generic Usenet Account | last post: by
44 posts views Thread by Bamber | last post: by
1 post views Thread by sva0008 | last post: by
13 posts views Thread by didacticone | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.