Difference between two pieces of code in PHP
I'm sorry if I'm asking something too specific, but I'm a beginner in PHP and this is kind of annoying me. I want to make a function to do some data processing and send an e-mail, but when I put the e-mail function inside another function, it doesn't work. Why does this happen?
This works:
if (do some checking) {
//...
if (mail($to, $subject, $body)) {
echo 1;
} else {
echo 2;
}
} else {
echo 3;
}
This do开发者_高级运维esn't work (I cut the code out to this, and it still doesn't work):
function sendMail($to, $subject, $body) {
if (mail($to, $subject, $body)) {
return 1;
} else {
return 2;
}
}
//...
if (do some checking) {
//...
echo sendMail($to, $subject, $body);
} else {
echo 3;
}
This worked fine for me.
<?php
function sendMail($to, $subject, $body) {
if (mail($to, $subject, $body)) {
return 1;
} else {
return 2;
}
}
if (true) {
echo sendMail('some@email.org', 'some subject', 'some body');
} else {
echo 3;
}
?>
I get 1 echoed. So sendMail function definately works.
What "do some checking" is resolved to in your script? Check that.
Is the output 1, 2, or 3 when you run your script?
Try the following: (btw, you need to replace 'email@example.com' with a valid email you can check)
<?php
function sendMail($to, $subject, $body) {
if (mail($to, $subject, $body)) {
return 1;
} else {
return 2;
}
}
if (1) {
$to = "email@example.com";
$subject = "Message Subject";
$body = "Message Body";
echo sendMail($to, $subject, $body);
} else {
echo 3;
}
?>
精彩评论