无法更改所需文件中的 PHP 变量

Can't change PHP variable in required file

这个问题有点棘手。

我同时发送两封电子邮件。我有一个脚本,email_template.php,其中包含:

<?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>";
?>

基本上,一个简单的电子邮件模板。

现在,我正在尝试更改 $subject$content 的值以适应两个不同的电子邮件:

$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>");

为什么在我需要模板文件后不能更改变量的值,我该怎么做?

执行$body = "..."语句时,$content变量的值被插入到$body中。所以在 require_once 调用之后,$body 没有对 $content 的引用;它只是具有执行时 $content 的任何值。

作为替代方案,您可以执行以下操作:

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

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

注意使用 require 而不是 require_once