1
votes

I want to have a function which takes 1 parameter as input, if no value is passed it should take default value as another function's output. Am using Class in PHP to achieve this but it's giving me error as "Constant expression contains invalid operations"

<?php

class Common
{
    public $usrname;

    function getLoggedInUser(){
        if (ISSET($_SESSION['email'])) {
            $this->usrname = ($_SESSION['email']);
            return $this->usrname;
        }
        return false;
    }

    function getLoggedInUserId($username = $this->usrname){
        echo $username;
    }

}

And calling the class file as

    <?php
    include "common.php"
    $c = new Common;
    $c->getLoggedInUserId();

Below is the error is shown for above call

Fatal error: Constant expression contains invalid operations

Please let me know how to pass function result as parameter for another function. Thanks

3

3 Answers

1
votes

As a default value has to be a constant value, you would need to write something like this...

function getLoggedInUserId($username = null){
    if ( $username == null ) {
       $username = $this->usrname;
    }
    echo $username;
}
1
votes

getLoggedInUserId user must redefined as below

function getLoggedInUserId($username=""){
    if(empty($username)){
     echo $this->usrname;
    }else{
         echo $username;
    }

}
1
votes

change your function to this:

public function getLoggedInUserId($username=""){
    $username = ($username == "") ? $this->usrname : $username;
}