Reputation: 918
I'm trying to setup a mailing system for my first time. I'm using PHPMailer but ,since there are quite a lot of thing to set I wrap that in another class to make it easier for myself, I've got this Warning: Creating default object from empty value. My code is like.
class Mail{
public $m;
public function __construct(){
$m = new PHPMailer;
//config like isSMTP, Host, Username, Password etc.
}
}
but when is call method like
public function subject($subject){
$m->Subject = $subject;
}
and var_dump($m->Subject); I'll get Warning: Creating default object from empty value
My questions are
1.Why that error is occurring?
Upvotes: 0
Views: 2112
Reputation: 3832
One of the most important aspects of PHP's OOP support is the $this
pseudo-variable. It evaluates as an object's address in memory, which is why it's not really a variable since an object's address may be invariable. Without $this
, a method is unable to access the objects properties or other methods.
If a variable $whatever
appears in a method, nothing indicates that the variable has any relationship to the object; it's just a variable. The only way for PHP to access a property (or another method) is by means of $this
, since the pseudo-variable provides the object's address. If the property exists, it will be an offset from that address.
Note, you can do some powerful things with $this. For example, if you return that variable in a method, you can set up method chaining, as follows:
class test {
public $m;
public function setM( $num ){
$this->m = $num;
return $this;
}
public function getM(){
return $this->m;
}
}
echo (new test())->setM(15)->getM(); // 15
Live demo here
There appears to be a discrepancy between what the manual says about $this:
$this is a reference to the calling object ... (see http://php.net/manual/en/language.oop5.basic.php)
and PHP's internal source code which indicates that the pseudo-variable is actually a pointer (See PHP's internals here), despite the fact that PHP presents itself as not having pointers!
Whatever the true nature of $this, clearly it plays a critical role for a method to read and set member variables or to invoke another method.
Upvotes: 0
Reputation: 91744
If you want to access your class property in your methods, you need to use $this
:
public $m;
public function __construct(){
$this->m = new PHPMailer;
//config like isSMTP, Host, Username, Password etc.
}
...
public function subject($subject){
$this->m->Subject = $subject;
}
Upvotes: 3