Search code examples
phprequire

Can't change PHP variable in required file


This is a bit of a thorny problem.

I'm sending out two emails at the same time. I have a script, email_template.php which contains this:

<?php
  $body = "<!doctype html>
      <html>
      <head></head><body>
      <div id='wrapper' style='background: #eee;padding: 30px 0; font-family: Arial, sans-serif;'>
      <div id='admin-email' style='display: block; padding: 30px; width: 700px; margin: 0 auto; max-width: 90%; background: #fff;'>
        <h1 style='font-weight: 500;padding: 32px 16px; margin: -30px; margin-bottom: 20px; font-size: 36px; background: #1c5d99;color: #fff; text-align: center;'>
          My Heading
        </h1>
        <h1 style='font-weight: 400; font-size: 28px;margin-bottom: 32px;text-align: center;'>
          {$subject}
        </h1>
        {$content}
      </div>
      </body></html>";
?>

Basically, a simple template for an email.

Now, I'm trying to change the value of $subject and $content to fit the two different emails:

$name = "{$row["f_name"]} {$row["m_name"]} {$row["l_name"]}";
$to   = $row["email"];
$subject = "Registration Successful";
$content = "<p>Your registration for {$game["name"]} was successfully processed. <a href='http://{$domainname}/games/{$game["id"]}'>Click here</a> for more details.</p><p>";

require_once "../../admin/email/email_template.php";

// send_email is a custom function
send_email($to, $subject, $body, "myemail@email.com");

$subject = "$name has registered for {$game["name"]}";
$to = "Joe User <user@example.com>";

$re = $game["registered"] + 1;
$av = $game["available"];

// trying to reassign $content, but it doesn't work
$content = "<p>$name has registered for {$game["name"]}. There are now $re/$av spots left.</p>";

send_email($to, $subject, $body, "My Name <noreply@example.com>");

Why can't I change the values of the variables after I've required the template file, and how can I do this?


Solution

  • The value of the $content variable is interpolated into $body when the $body = "..." statement is executed. So after the require_once call, $body doesn't have a reference to $content; it just has whatever the value of $content was at the time it was executed.

    As an alternative, you could do something like the following:

    $content = 'First email contents';
    require('template.php');
    mail( ... $body ... ); // send first email
    
    $content = 'Second email contents';
    require('template.php');
    mail( ... $body ... ); // send second email
    

    Note the use of require instead of require_once.