I am trying to create a custom class that will handle mailing for me.
Here is my class (mailerclass.php) :
class Mailer {
// Private fields
private $to;
private $subject;
private $message;
// Constructor function
function __construct($to, $subject, $message) {
$to = $to;
$subject = $subject;
$message = $message;
}
// Function to send mail with constructed data.
public function SendMail() {
if (mail($to, $subject, $messagecontent)) {
return "Success";
}
else {
return "Failed";
}
}
}
When I try to call it here (index.php) I get a "Call to undefined function SendMail()" message?
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// Import class
include('mailerclass.php');
// Trim and store data
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
// Store mail data
if ($validated == true) {
// Create new instance of mailer class with user data
$mailer = new Mailer($to, $subject, $message);
// Send Mail and store result
$result = $mailer.SendMail();
}
Why does this happen ??
Dot .
is use for concatenate
. You use ->
to access member of class
$result = $mailer->SendMail();
You don't call class methods with a dot. You call class methods (not static) with ->
like:
$result = $mailer->SendMail();
Besides you need to set your properties with $this->
(again if not static) change the content of your contstructor to:
$this->to = $to;
$this->subject = $subject;
$this->message = $message;
Same goes for your mail()
function:
mail($this->to, $this->subject, $this->messagecontent)
You saw me mentioning static a few times, if you ever want to access a static property or method in your class you can use self::
.
is a contact operator, to access member of a class both variable and functions use ->
operator use the below code:
$result = $mailer->SendMail();
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.