How does "return" work in a function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bakertaylor28
    New Member
    • Feb 2021
    • 45

    How does "return" work in a function?

    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?

    Code:
    <?php
    
    function privcheck() {
     $priv = $_SESSION['priv'] ;
     return $priv;
    }
    
    if ( privcheck()=== 0) {
    echo 'do code for case 0';
    }
    
    if ( privcheck() ===1) {
    echo 'do code for case 1';
    }
    
    if ( privcheck() ===2) {
    echo 'do code for case 2';
    }
    
    exit;
    ?>
    Last edited by bakertaylor28; Mar 3 '21, 09:05 PM. Reason: minor correction in the code which was immaterial to the point.
  • AjayGohil
    New Member
    • Apr 2019
    • 83

    #2
    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.
    Like most of the programming languages, a function in PHP is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse.

    Comment

    • bakertaylor28
      New Member
      • Feb 2021
      • 45

      #3
      Which, from my understanding, is what the return is for in the function:
      Code:
       function privcheck() {
      $priv = $_SESSION['priv'];
      [B] return $priv;[/B]
      }
      So That, within the If statement the following become more or less equivalent:

      Code:
      if ( $priv === foo) {
      
      }
      Code:
      if ( privcheck() === foo) {
      
      }
      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.

      Comment

      Working...