PHP扩展类继承

时间:2013-02-10 13:41:45

标签: php

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

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

    }
}

3 个答案:

答案 0 :(得分:0)

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

print("user is: " . self::$username);

答案 1 :(得分: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');

答案 2 :(得分: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);