1

我有 2 个班级profile还有loginUser一个extends-class 。 当用户登录并且一切都通过验证时,我会: profile

$login = new loginUser();
$login->set_status(true);
$login->set_accessClearance($get['access']);  //  integer fetched from database
$login->set_userName($get['user_name']);  //  string fetched from database

类 loginUser 扩展个人资料:

class loginUser extends profile
{   
#   update status in profile
    public function set_status($bool){
        $this->loggedIn = $bool;
    }
//
#   set users access clearance into profile
    public function set_accessClearance($int){
        $this->accessClearance = $int;
    }
//
#   set username into profile
    public function set_userName($str){
    $this->userName = $str;
    }
//
}

loggedIn,accessClaranceuserName是-protected中的变量。 profile

什么都不会写到我profile班级
我知道值是从数据库中获取的;当我var_dump()直接对其进行操作时,$login它会保存预期的数据……我做错了什么?

班级简介

class profile
{
    protected $loggedIn = false;
    protected $accessClearance = 0;  //  0 = denied
    protected $userName;

    public function get_status(){
        return $this->loggedIn;
    }   
    public function get_accessClearance(){
        return $this->accessClearance;
    }
    public function get_userName(){
        return $this->userName;
    }
}

如果有帮助,我已经用我的班级完成了profile这个

session_start();
    $_SESSION['profile'] = new profile();
4

4 回答 4

2

问题是实例和类之间的区别。您的 $_SESSION['profile'] 设置为配置文件的实例。profile 可以有很多实例(您的用户登录是另一个),并且一个中的数据不要修改其他中的数据。这是面向对象编程的基本范式。

您的问题的解决方案可以采用多种形式。您可以将 $_SESSION['profile'] 重新分配给新创建的用户,这可能是最简洁的方式。或者,您可以探索在 Profile 类上使用静态访问器和静态属性,这将保证范围内只有一个配置文件。

其他方法变得更高级,例如对象组合(也许配置文件包含用户等)、单例(Profile::getProfile()Profile::setProfile($logged_in_user))等。

于 2012-07-10T16:46:51.357 回答
1

您通过将扩展user objectauthentication object.

您应该通过使用对象组合来使用更好的会话和身份验证机制。

于 2012-07-10T16:46:13.780 回答
0

也许我误解了你,但你可能不理解扩展类是如何工作的。当您声明loginUser为 的扩展时profile,这意味着 的任何实例都loginUser将具有配置文件的属性。但是,这并不意味着所有loginUser对象都会影响所有配置文件对象。类只是抽象定义,它们不是您可以在程序中使用的实际事物。

于 2012-07-10T16:45:55.480 回答
0

我认为,您误解了面向对象编程的目的。这些变量只写入子类,因为您创建了类 loginUser 的对象,而不是配置文件 - 继承起作用,而不是向上 + 如果您希望将这些变量写入配置文件类,您应该将它们写入配置文件类:)。或者只是在配置文件类中设置静态:)

于 2012-07-10T16:47:30.917 回答