2016-03-02 18 views
1

我有這樣的代碼:我在班級以外有108個變量,我是否需要將其全部聲明爲全球?

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類以外的變量?

謝謝你,我真的很感謝你的答案

+1

您可以在一個陣列歸還或者你可以把它們放到一個公共屬性。 (另外,如果我看到'$ body_txt_1',你可能想用數組來看看) – Rizier123

回答

1

你必須從全球,它是邪惡的! :)
第一件事情,你可以把你所有的global $mandrill_*;的屬性文件,並使用parse_ini_file
也將加載/讀取它們,我建議你把所有的模板不同XML/XSDJSON文件,並創建一個性能/ INI文件,你會把自己的路...

2

這是從來沒有把你的變量的全局狀態是個好主意。它可以使測試和調試成爲一場噩夢。我建議你創建一個Config()類並把你的變量放在那裏。這個類可以有一個getConfig($itemName)方法,它將返回你請求的變量的值。

+0

歡迎來到SO :)不錯的答案:)但我認爲它更配合存儲任何與配置相關的配置文件夾/文件 –

+0

@HalayemAnis同意。這就是大多數框架和應用程序所做的。但是從全局變量到配置文件可能太多了。所以,如果我們在課堂上開始使用它可能會更好。 –

相關問題