您观察到的可能是其他框架用于用户会话处理的包装对象。
将代码更改为对象将是一种很好的做法,并且可以像这样工作:
<?php
/** Session.php */
class Session
{
protected $isAdmin = 0;
public function __construct()
{
// ... do your session initialisation here ...
if (USER_HAS_SOMESPECIAL_RIGHTS)
$this->isAdmin = 1;
}
/**
* Do we have admin rights?
* @return bool
*/
public function isAdmin() {
return $this->isAdmin;
}
/**
* Echoing out the current role in the system
* @return string
*/
public function getRole() {
if ($this->isAdmin)
return "admin";
return "normal mortal being (at least not an admin)."
}
}
用法:
include 'Session.php';
$session = new Session(); // This is when your code in __construct will be evaluated
echo $session->getRole();
当然这只是一个简单的例子,一旦你进入 OOP,你会发现你可以在更大程度上抽象它。希望这可以帮助!