PHP:无法访问父类变量

时间:2012-01-28 06:45:40

标签: php

我正在尝试从父类访问变量,如下所示:

 //PARENT CLASS
class InfoString{
    private $username = "JOE";

    public function _construct(){}

    protected function get_username(){
        return $this->username;
    }         
}


class Service extends InfoString{
    //this class should now inherit the variables in InfoString, right??
    public function _construct(){}

    public function hello_username(){
        echo "HELLO! ". parent::get_username(); 
    }
}

我打电话给这个班:

$a = new Service();
$a->hello_username(); //prints nothing, instead of the username

而不是得到“HELLO!JOE”,我得到一个空字符串。我在这里做错了什么?

另外,假设类'InfoString'将包含配置参数 - 扩展这个类是一个好主意,或者从适当的实现获取配置变量,比如'InfoString'类到另一个类? ?

感谢。

1 个答案:

答案 0 :(得分:2)

您只是展开InfoString,因此您只需使用$this->get_username();即可。 ::用于调用静态方法。

此外,如果您提高错误级别,则会收到错误消息。致电error_reporting(E_ALL);这将为您提供解决未来类似问题的线索。

相关问题