PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     php, phpmailer     No comments   

Issue

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?


Solution

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.



Answered By - Synchro
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing