Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

some questions about store datas on variable in class on php8

I don’t know if I do something wrong, please help solve this problem

when I tried to use variable in class to store data just like

class Send
{
    private $_email;
    
    public function sendMail()
    {
        $this->_email->to = 'xxx';
        
        $this->do();
    }

    public function do()
    {
        // code    
    }
}

in the function sendMail() I tried to use $this->_email->to to store user’s mail, and in function do() to read it, but some error occurred, it tells me that Attempt to assign property "to" on null

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and I remember it will be work in php 7.x

>Solution :

In PHP you can just assign values to a variable of a simple datatype like string or integer, but this is not true for objects.

Objects need to be instantiated first, using the new keyword.

public function sendMail()
{
    $this->_email = new Email();
    $this->_email->to = 'xxx';
    $this->_email->sendMail();
}

The class Email of course has to be defined first. It can have properties and methods for all of your needs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading