AntonioJunior
AntonioJunior

Reputation: 959

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 doesn'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;
}

Upvotes: 0

Views: 96

Answers (2)

Andrew Haller
Andrew Haller

Reputation: 270

Is the output 1, 2, or 3 when you run your script?

Try the following: (btw, you need to replace '[email protected]' 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 protected]";
    $subject = "Message Subject";
    $body = "Message Body";
    echo sendMail($to, $subject, $body);
} else {
    echo 3;
}
?>

Upvotes: 0

ThatGuy
ThatGuy

Reputation: 15099

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('[email protected]', '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.

Upvotes: 2

Related Questions