A Viewstate for PHP
There is, however, one difference. $_SESSION is unique to a user but is reused across pages. With only one window to your website, the two preform the same function. But if a user has multiple tabs or windows, $_SESSION can change in between what would otherwise be two successive page loads.
The viewstate has two functions:
Storing properties for controls and forms, Storing arbitrary dataThe viewstate is responsible for ensuring a red label is still red (and doesn’t default back to black) between page loads. Controls and forms manage this transparently from the developer (excluding a non-obtrusive ViewState property on controls). There is also a viewstate on the page object. It will act like a dictionary, allowing you to save arbitrary data to it.
The viewstate is a magical thing, and it achieves that through indirection. It is what separates a browser form submission from a user actually preforming an action. Prado and Fortitude both duplicate this functionality in PHP.
For a full example, take a look at Fortitude Form’s code. But for today’s purposes, I just wanted to demonstrate how to create a simple viewstate in PHP.
count++;} else {$viewstate = new stdObject;$viewstate->count = 0;}?>Page-load count: =$viewstate->count;?>
It preforms very similarily to $_SESSION. Although I used an object, it works just as well with an array. But it accomplishes a separate scope for each page. Frequently in PHP, pagination results are placed in $_SESSION, but that means only one set can be used at a time without butchering the rest. In a page scope, any manipulations can be done at will. And that exposes the real difference between the two: global things, like login operation or options, should be set in $_SESSION. Local, page-level or temporary things should be set in the page’s viewstate. Opening two or three or even one hundred twenty copies of that script will maintain that many instances of $viewstate->count. $_SESSION maintains only one.
Note that the security problems the ExtremeExperts article mentions are just as true with PHP as ASP.net. A manipulative user could set viewstate to a custom crafted value and disrupt the applications expectations. But that just means judicious amounts of validation are required before consuming viewstate on postbacks. Both ASP.net and PHP’s viewstate can be made secure.
上一篇: php 字符串替换的方法_PHP教程
下一篇: 【一句话代码】最轻最小的JQ提示层代码