-1

All examples I can find on the internet seem to show using the indexing operator for $_GET and $_POST.

For example, I would think you could write:

<?php
    echo $_GET->parameterName;
?>

instead of

<?php
    echo $_GET['parameterName'];
?>

I get this error when I try the first piece of code:

NOTICE Trying to get property of non-object on line number 2
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
  • 1
    No, that is not possible. `$_GET` is not an object. it is an array. – castis Feb 21 '18 at 15:51
  • No, because the global variables `$_GET` and `$_POST` are an array. You can cast it to an object though. – Daan Feb 21 '18 at 15:51
  • `->` is an [operator](https://stackoverflow.com/q/2588149/1415724), so you can't use that method. This besides the other comments above. – Funk Forty Niner Feb 21 '18 at 15:51
  • Strange that you would ask this question. Did you try it? What were your results? And why would you think that it was available? – random_user_name Feb 21 '18 at 15:52
  • 1
    just for curiosity sake, what did this `echo $_GET->parameterName;` give you? please turn on `error_reporting(E_ALL);`. That's how you'll learn – Rotimi Feb 21 '18 at 15:52
  • 3
    if you really hated yourself and the other devs you might ever work with, you could `$_GET = (object) $_GET;` and then it would work. terrible idea though, its only neat for the sake of it. – castis Feb 21 '18 at 15:52
  • NO: you cannot access property of non-object. Note: it is not recommended to use global variables directly. You can wrap it into some custom object, introduce sanitation, validation etc. - this will make your code more readable. – Kamil Adryjanek Feb 21 '18 at 16:02

2 Answers2

2

IMO, you should not directly cast it to an object, instead you should use ArrayObject, which will allow you to access both as an array or as an object.

<?php
$_GET['parameterName'] = 'foo';

$_GET = new ArrayObject($_GET);
$_GET->setFlags(ArrayObject::STD_PROP_LIST | ArrayObject::ARRAY_AS_PROPS);

echo $_GET->parameterName.PHP_EOL;
echo $_GET['parameterName'].PHP_EOL;

foreach ($_GET as $key => $value) {
    echo $key.' => '.$value.PHP_EOL;
}

https://3v4l.org/FmYIQ

Result:

foo
foo
parameterName => foo
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You can cast $_GET as object:

$getObj = (object) $_GET;

Maybe this is also working:

$_GET = (object) $_GET;
ManuKILLED
  • 71
  • 1
  • 11