natwaalf twaalf
natwaalf twaalf

Reputation: 105

Best practice to return a variable when you're not sure if it exists

Lets say I want to return an object with information about the client who requests a page. I take PHP as an example. Something like this:

public function getClientInformation(){
    return [
        "ip" => $_SERVER["REMOTE_ADDR"],
        "request_uri" => $_SERVER["REQUEST_URI"],
        "refferer" => $_SERVER["HTTP_REFERER"]
    ];
}

The problem is: I don't know if the referrer is set. How do I check properly if it is set and return false if it doesn't? This is something I came up with but I don't like it:

public function getClientInformation(){
    $referrer = false;
    if(array_key_exists("HTTP_REFERER", $_SERVER)){
        $referrer = $_SERVER["HTTP_REFERER"];
    }

    return [
        "ip" => $_SERVER["REMOTE_ADDR"],
        "request_uri" => $_SERVER["REQUEST_URI"],
        "refferer" => $referrer
    ];
}

I would appreciate your help

Upvotes: 0

Views: 145

Answers (2)

MAZux
MAZux

Reputation: 981

In php you may use the [Error Control Operators][1], something like this:

public function getClientInformation(){
    return [
        "ip" => $_SERVER["REMOTE_ADDR"],
        "request_uri" => $_SERVER["REQUEST_URI"],
        "refferer" => @$_SERVER["HTTP_REFERER"]
    ];
}

Which gonna return false if there is a warning (in case calling undefined index) or an error, but be sure where to use it.

Or you could use the inline ? operator:

public function getClientInformation(){
    return [
        "ip" => $_SERVER["REMOTE_ADDR"],
        "request_uri" => $_SERVER["REQUEST_URI"],
        "refferer" => isset($_SERVER["HTTP_REFERER"])? $_SERVER["HTTP_REFERER"] : false
    ];
}

In php 7.0 there is the [null coalesce operator][2] ??:

public function getClientInformation(){
    return [
        "ip" => $_SERVER["REMOTE_ADDR"],
        "request_uri" => $_SERVER["REQUEST_URI"],
        "refferer" => $_SERVER["HTTP_REFERER"] ?? false
    ];
}

Which is a shorthand for the above code. [1]: http://php.net/manual/en/language.operators.errorcontrol.php [2]: https://www.php.net/manual/en/migration70.new-features.php

Upvotes: 0

Khem
Khem

Reputation: 184

"refferer" => $_SERVER["HTTP_REFERER"] ?? false; // PHP 7 
"refferer" => isset($_SERVER["HTTP_REFERER"]) ?: $_SERVER["HTTP_REFERER"] : false; // < PHP 7

Upvotes: 1

Related Questions