如何在php中向父类中添加值


How do I add a value into parent class in php

我有两个类,profile和一个loginUserextendsprofile-
当用户登录并且所有内容都通过验证时,我会:

$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

class login用户扩展配置文件:

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;
    }
//
}

loggedInaccessClaranceuserNameprofile-中的protected变量。

没有任何内容被写入我的profile-
我知道值是从数据库中提取的;当我直接在$login上执行var_dump()时,它会保存预期的数据。。。我做错了什么?

类配置文件

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();

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

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

其他方法变得更高级,例如对象组合(可能概要文件包含用户等)、singleton(Profile::getProfile()Profile::setProfile($logged_in_user))等。

您将user object扩展为authentication object违反了单一责任原则。

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

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

我认为,您误解了面向对象编程的目的。这些变量只被写入子类,因为你创建了类logiUser的对象,而不是profile-继承是向下的,而不是向上的+如果你想把这些变量写入profile类,你应该把它们写入profile类:)。或者在配置文件类中使其为静态:)