0

我有一个要扩展的基类,但我无法弄清楚为什么我在基类中定义的变量不能被子类访问。我知道它们必须受到保护才能允许访问,但它们仍然对我不起作用。

class user {

    protected static $username;
    protected static $password;
    protected static $remember;

    function __construct() {

    }

    public function login($username, $password, $remember) {

        $this->username = $username;
        $this->password = $password;
        $this->remember = $remember;

        $login = new login();

    }

}

class login extends user {

    function __construct() {

        print("user is: " . $this->username);

        die();

    }
}
4

3 回答 3

0

因为变量应该是非静态的。如果你想要静态变量(就像你知道的那样)它应该看起来像这样

print("user is: " . self::$username);
于 2013-02-10T13:44:27.353 回答
0

这会更有意义:

class user {

    protected $username;
    protected $password;
    protected $remember;

    public function __construct($username, $password, $remember) {
        $this->username = $username;
        $this->password = $password;
        $this->remember = $remember;
    }

    public static function login($username, $password, $remember) {
        return new login($username, $password, $remember);
    }

}

class login extends user {

    public function __construct($username, $password, $remember) {
        parent::__construct($username, $password, $remember);

        print("user is: " . $this->username);

        die();

    }
}

$foo = new user::login('foo', 'bar', 'meh');
于 2013-02-10T13:49:14.013 回答
0

基类中的变量是静态的,可以更好地理解继承。

你需要这个:

class user {

    protected $username;
    protected $password;
    protected $remember;

    public function __construct($username, $password, $remember) {
        $this->username = $username;
        $this->password = $password;
        $this->remember = $remember;
    }
}

class login extends user {

    public function __construct($username, $password, $remember) {
        parent::__construct($username, $password, $remember);
        print("user is: " . $this->username);
    }
}

$user = new login('joe bloggs', 'a password', TRUE);
于 2013-02-10T13:51:08.787 回答