如何从构造函数获取变量,以便可以在其他函数中使用?

时间:2016-03-02 15:16:59

标签: php

我有这段代码:

<?php

class Email{
    public $mandrill_host;

    public function __construct() {
        $this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
        $this->mandrill_host = $config_ini['mandrill']['host'];

    }

    public function sendEmail () {
        $res = $this->mandrill_host;
        return $res;    
    }
}

$test = new Email;
echo $test->sendEmail ();

?>

它给了我一个空洞的结果。似乎构造函数方法没有给出sendEmail函数中所需的变量。即使我已经在班级声明为公共变量。

如何从构造函数中获取$this->mandrill_host,以便我可以在任何其他方法中使用它?我在这里想念的是什么?

1 个答案:

答案 0 :(得分:0)

尝试
    

class Email{
    public $mandrill_host;
    public $config_ini; //you are missing this

    public function __construct() {
        $this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
        $this->mandrill_host = $this->config_ini['mandrill']['host'];

    }

    public function sendEmail () {
        $res = $this->mandrill_host;
        return $res;    
    }
}

$test = new Email;
echo $test->sendEmail ();

?>