2

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 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

getLoggedInUserId user must redefined as below

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

}

Comments

1

change your function to this:

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

1 Comment

Thanks for the help. Got it :)

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.