Search code examples
phpsuperglobals

Wrap superglobal $_GET inside a class property


The goal is to get some precise values of $_GET in a property of a class while:

  1. removing any key not desired
  2. defaulting values when keys are not defined

With this code in a file /request.php:

$req = new request();
var_dump($req);
class request {
  private $Get;
  function __construct() {
    $this->Get = filter_input_array(INPUT_GET,array (
      'menu'=>array (
        'filter'=>FILTER_VALIDATE_INT,
        'options'=>array (
          'default'=>30,
        ),
      ),
    ));
  }
}

from php's man page for filter_input_array() about the third parameter (true by default):

Add missing keys as NULL to the return value.

I would expect that calling domain.com/request.php would yield a defaulted [sic] array with the integer 30 as menu's value. however when no $_GET are defined (that is, when there's no character after a question mark in the url) filter_input_array returns null therefore the var_dump is this:

object(request)#1 (1) { ["Get":"request":private]=> NULL }

however when $_GET is defined (that is, having at least one character after the question mark in the url) such as calling domain.com/request.php?a will yield:

object(request)#1 (1) { ["Get":"request":private]=> array(1) { ["menu"]=> NULL } }

How can I force filter_input_array() to return an array so that default values will be built even if I call an url with no $_GET value defined like index.php?

It seems possible to rewrite a request from .htaccess so that I could mimic a $_GET value being defined if there are not, but it feels weird.


Solution

  • Why not to use another simple way?

    var_dump(filter_var_array($_GET, array(
      'key' => FILTER_DEFAULT,
    ), true));