开发者

Difference between two PHP variable definitions

I have two variable definitions, and I am trying to understand the difference between the two so I can merge them into one.

PHP Definition 1:

$page =开发者_StackOverflow $_GET['page'];

PHP Definition 2:

$page = 0;
 if(isset($_GET['page'])){
    $page = (int) $_GET['page'];
 }


Your second definition will suppress any error encountered when $_GET['page'] isn't set by not trying to assign it to anything.

The (int) part in the second definition will cast $_GET['page'] to an integer value. This will inhibit any attacks you might get, although you should still be careful.

Finally, $page = 0 simply sets a default value for $page. If there is no value in $_GET, $page will remain with a value of 0. This also ensures that $page is always set, if you're using it in code below your snippet.

I don't know what you mean by merge them into one; the second snippet is an extension (and improvement) of the first.


The first code block assigns to $page whatever value is in $_GET['page'].

The second one assigns a default value of 0 to $page. And the if statement will check first to see if $_GET['page'] is set (to avoid warnings). If it is set indeed, it will cast the value of $_GET['page'] to an integer and assigns it to $page.


I'd personally use:

$page = isset($_GET['page']) ? (int) $_GET['page'] : 0;

Or array_key_exists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜