KMC
KMC

Reputation: 1742

Proper way to initialize property of class

I have a class with a property. The way I implemented is that the object is initialized in the constructor and its properties are initialized separately inside another method. So here's what it looks like -

require_once('PHPMailerAutoload.php') 
class myclass {
    private $mailer;
    public function __construct() {
        $this->mailer = new PHPMailer;
    }
    public function set($host, $to) {
      var_dump($this->mailer) // This returns object structure
      $this->mailer->Host = $host;
      $this->mailer->to = $to;
   }
}

However, I'm getting "Trying to get property of non-object" notice even though mailer property is already initialized with PHPMailer.(I tested with var_dump as shown in the code) I could suppress it with "@", but I'm looking for better solution if there's any. Thanks.

Upvotes: 0

Views: 137

Answers (1)

Jordy
Jordy

Reputation: 1049

You are trying to store the mailer from your constructor but you do not have a variable called $mailer set.

Also in PHPMailer everything starts capitalized so To would also have to be capitalized.

You are also missing semicolumns.

require_once('PHPMailerAutoload.php');

class myClass {
    private $mailer;

    public function __construct() {
        $this->mailer = new PHPMailer;
    }

    public function set($host, $to) {
      var_dump($this->mailer);
      $this->mailer->Host = $host;
      $this->mailer->To = $to;
   }
}

Then you wanna access it like this.

$test = new myClass();
$test->set("asdf", "[email protected]");

Upvotes: 2

Related Questions