简体   繁体   中英

How to create an object of a class from another class in PHP?

I have been trying to create an object of a PHPMailer() class in another class but it just doesn't work.

I have included all the files like in my main index.php file

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require "assets/PHPMailer/src/PHPMailer.php";
require "assets/PHPMailer/src/Exception.php";
require "assets/PHPMailer/src/SMTP.php";

these have been imported successfully because if I declare

 $mail = new PHPMailer();

in this file then the mail object is created.

But, I want to this in a specific function of another class. I have a class Projects and in it, I have defined a public static function do_request() which sends an SQL query to a database. This function works perfectly fine, but now I want to send an email whenever this function is called. For that, I created a new public function send_email() in the same class and I call it from the public static function do_request() . In the send_email() function when I declare

 $mail = new PHPMailer();

the code crashes and my object is not created anymore. Can anyone tell me what might be wrong here?

Any time you're getting a crash, the first place to look is your web server's error log.

In the absence of your actual code or any error messages, we can only guess at the cause.

If you have those require statements inside a function that you all, it will fail the second time you call it because you're loading duplicate classes. This is also a very good reason to learn to use composer, as it means you don't have to worry about loading classes manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM