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

Instantiate Class from method return and pass data to constructor PHP

I have notification classes called ProductNotification, OrderNotification, etc, these have a mail method which returns another class which holds further data for the sending of emails:

class ProductNotification {
    public function mail()
    {
        return ProductMail::class;
    }
}
class OrderNotification {
    public function mail()
    {
        return OrderMail::class;
    }
}

Is there a way to instantiate the ProductMail class from the method, the following doesn’t work and I’m not sure how to pass through another variable $data to the constructo.?

class BaseNotification {
    public function toMail()
    {
        return (new $this->mail())->to($email)->send();
    {
}

I know that if mail() was a property on the class instead, that this would be possible and I can pass through $data to the constructor as the following works, but is this possible from a method?

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

class ProductNotification {
    public $mail = ProductMail::class;
}
class BaseNotification {
    public function toMail()
    {
        return (new $this->mail($data))->to($email)->send();
    {
}

>Solution :

You can store the class as a local variable in the toMail method and then instantiate it.

class BaseNotification {
    public function toMail($data)
    {
        $mail_class = $this->mail();

        return new $mail_class($data);
    }
}
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