View Full Version : mail() as a variable?

01-08-2012, 08:11 PM
I want to do this:


$function_a = mail('me@mydomain.com', 'Test Subject', 'Test message.');

if ($function_a) { echo "Success!"; } else { echo "Failure!"; }


When I run this, the mail is sent in the definition and not the if statement. Is there a way I can prevent the mail from being sent until the "if"? Thanks ...

01-08-2012, 09:25 PM
try this-


if ($function_a = mail('me@mydomain.com', 'Test Subject', 'Test message.')) { echo "Success!"; } else { echo "Failure!"; }


01-08-2012, 09:34 PM
Not sure what you're trying to do.

If you're trying to determine if the function exists:
if (function_exists('mail'))

IF you're trying to whether mail returned true, then as nomanic says.

01-08-2012, 10:05 PM
Thanks for the replies.

nomanic, that works - I've used it before. But I'm trying to list a series of functions and submit them at the end with the if statement.

tangoforce, I'm trying to list multiple mail functions by variables and make sure they (all) were successful by the if statement at the end.

Thanks ...

01-09-2012, 01:18 PM
you only need to test the return values in the if condition

$r1 = mail(...);
$r2 = mail(...);

if ($r1 && $r2)
// all success

01-09-2012, 04:59 PM
Dormilich, thanks.

When I run that, it sends the mail from the definition and not the if (I think, because if the if is deleted, the mails are still sent).

01-09-2012, 05:19 PM
The if doesn't check if the mails are sent or not, it only checks if it was queued to the mail program. The only time it will ever return false is if there is an issue contacting the smtp.

Not sure exactly what you are looking for either. As soon as mail() is called as a function it executes at this point. You capture the results into the variable (optional) and use an if to see if it was queued. If you are looking to capture the signature definition, you can do it either as a callable type:

$fpFunc = 'mail';
$fpFunc('to@to.com', 'subject', 'body', ...);
// or
call_use_func($fpFunc, 'to', 'subject', 'body', ...);
// can be checked:
if (function_exists($fpFunc))
$fpFunc('to', 'subject', 'body');

And the other option is via ReflectionFunction and calling the ->invoke method.

If its just a matter of checking the results for each, then you can use an array to capture the results. The only thing to note is that this result does not indicate if a user received an email, as that cannot be detected in PHP.

01-12-2012, 02:48 AM
Thanks, Fou-Lu. That's interesting.

I guess what I want isn't really possible. I have a cron setup to run a php script, which generates contents from a database and sends an email. I wanted it to send me an email if the cron failed somehow, but I guess I'll just make a mail function at the end so I know if it gets stuck ...