Search code examples
phpclassdefault

PHP use $_SESSION variable as default in class function


I have a class that interfaces a lot with the $_SESSION variables. Some functions should default to the current user if none is specified. I have the user id in $_SESSION['userid'] and use it in some places fine. However, when I try to use the $_SESSION variable as a default for function parameters I get an error. What would be the best way to go about doing this?

Here's the error I get:

Fatal error: Constant expression contains invalid operations in main.php on line whatever

<?php
class User {

    public function log_out() {
        unset($_SESSION['userid']);
    }

    public function get_data($uid = $_SESSION['userid']) {

    }

    public function logged_in() {
        return isset($_SESSION['userid']);
    }

    public function enabled($uid = $_SESSION['userid']) {

    }

}
?>

Solution

  • You cannot use a variable in the method signature. You can default $uid param to null. Then in the function body use the value from the session if $uid is null.

    Example

    You're not able to do this:

    public function get_data($uid = $_SESSION['userid']) {
    
    }
    

    But, this is fine:

    public function get_data($uid = null) {
        $uid = $uid ?? $_SESSION['userid'];
    }