我在类外有 108 个变量,我需要将其全部声明为全局变量吗?


I Have 108 Variables Outside The Class, Do I need To Declare It All As Global?

我有这段代码:

require_once ($_SERVER["DOCUMENT_ROOT"] . '/config.php');
require_once ($_SERVER["DOCUMENT_ROOT"] . '/lib/phpmailer/PHPMailerAutoload.php');
require_once ($_SERVER['DOCUMENT_ROOT'] . '/assets/messaging/email-template.php');  // This is where the templates stored
class Email {
    public function sendEmail ($send_to_email, $sent_to_name, $template_name) {
        // this variables stored in config.php
        global $mandrill_host;          
        global $mandrill_port;
        global $mandrill_username;
        global $mandrill_password;
        global $mandrill_from;
        global $mandrill_from_name;
        $mail = new PHPMailer;
        $mail->IsSMTP();
        $mail->Host = $mandrill_host;
        $mail->Port = $mandrill_port;
        $mail->SMTPAuth = true;
        $mail->Username = $mandrill_username;
        $mail->Password = $mandrill_password;
        $mail->SMTPSecure = 'tls';
        $mail->From = $mandrill_from;
        $mail->FromName = $mandrill_from_name;
        $mail->AddAddress($send_to_email, $sent_to_name);
        $mail->IsHTML(true);
        // I will have CASE here to select $subject, $body and $body_txt
        // from /assets/messaging/email-template.php
        // based on $template_name parameter
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = $body_txt;
        if(!$mail->Send()) {
           echo 'Message could not be sent.';
           echo 'Mailer Error: ' . $mail->ErrorInfo;
           exit;
        }
    }
}

问题是,我email-template.php文件中有 36 个不同的电子邮件模板。 每个模板都有 3 个不同的变量: $subject_1, $body_1, $body_txt_1

我是否必须将所有这些变量声明为全局变量? 或者还有另一种更好的方法在 PHP 类之外使用变量?

谢谢你,我真的很感激你的回答

将变量置于全局状态从来都不是一个好主意。它可能使测试和调试成为一场噩梦。我建议您创建一个Config()类并将变量放在那里。此类可以有一个 getConfig($itemName) 方法,该方法将返回您请求的变量的值。

你必须逃离全球,这是邪恶的! :)
首先,您可以将所有global $mandrill_*;放在属性文件中,并使用parse_ini_file
加载/读取它们另外,我建议您将所有模板放在不同的 xml/xsdjson 文件中,并创建一个属性/ini 文件,您将在其中放置它们的路径......