2011-10-03 76 views
2

有沒有辦法讓isDevMode,devModeToEmailAddress,devModeFromEmailAddress成爲私有屬性?ColdFusion 9 CFScript私有屬性和公共屬性

代碼:

/** 
* email 
* @accessors true 
*/ 
component email output="false" hint="This is email object." { 

/* properties */ 
property name="toEmailAddress" type="string"; 
property name="fromEmailAddress" type="string"; 
property name="subject"   type="string"; 
property name="body"    type="string"; 
property name="attachments"  type="array"; 

/* 
private isDevMode 
private devModeToEmailAddress 
private devModeFromEmailAddress 
*/ 

} 
+0

你有什麼打算?屬性(除其他外)在CF中定義訪問器,這意味着它們應該可用於訪問(因此不是私有的)。你是否試圖對ORM中的私有變量執行關係映射?或者,你是否「只想要一些私人變量」 - 如果是後者,你會想將它們設置在「變量」範圍內。 –

+0

我沒有使用ORM我只是想要只能在對象內部設置的屬性,而不能通過對象之外的東西來設置屬性。這樣,如果網站在devmode中,電子郵件不會發送給客戶,但是在生產時它們工作得很好。 –

+0

丹的答案在下面是你想要的。 –

回答

7

您可以添加setter="false"getter="false"防止getter和setter方法,但是你不能直接限制訪問性能。你最好的選擇是把它們放到組件本地作用域中的構造函數中。

/** 
* email 
* @accessors true 
*/ 
component email output="false" hint="This is email object." { 

isDevMode = false; 
devModeToEmailAddress = "[email protected]"; 
devModeFromEmailAddress = "[email protected]"; 

/* properties */ 
property name="toEmailAddress" type="string"; 
property name="fromEmailAddress" type="string"; 
property name="subject"   type="string"; 
property name="body"    type="string"; 
property name="attachments"  type="array"; 


} 

然後,當你需要使用這些功能,只需引用variables.isDevMode在任何功能,拿起值。如果您需要在運行時設置它們,則可以將它們設置爲您的函數的init()方法。我通常不喜歡這樣寫道:

component email output="false" hint="This is email object." { 

    instance = {}; 

    /* properties */ 
    property name="toEmailAddress" type="string"; 
    property name="fromEmailAddress" type="string"; 
    property name="subject"   type="string"; 
    property name="body"    type="string"; 
    property name="attachments"  type="array"; 


    public email function(required boolean isDevMode, required string devModeToEmailAddress, required string devModeFromEmailAddress){ 

     variables.Instance.isDevMode = Arguments.isDevMode; 
     variables.Instance.devModeToEmailAddress = Arguments.devModeToEmailAddress; 
     variables.Instance.devModeFromEmailAddress = Arguments.devModeFromEmailAddress; 

    { 

} 

然後,任何時候,我需要這些值我只是得到variables.Instance.isDevMode。我還創建了一個通用的get()方法,將返回variables.instance,以便我可以看到裏面有什麼。

public struct function get(){ 
    return Duplicate(variables.Instance); 
} 

但是,因爲這些位於組件的局部變量範圍內,所以它們不能從組件外部修改。

+2

我認爲你仍然可以通過引用修改結構。所以你可能希望在返回結構之前複製()該結構。 – Leigh

+0

你絕對正確。相應地調整代碼。 –