2013-05-19 33 views
0

我只是想確保我正確地做到了這一點。我有點困惑$this->parameter,$parameterpublic $parameter正確執行對象參數

這是我正在做的一個例子。我希望任何聲明爲公開的東西都可以通過$instance->parameter方法訪問。這是否意味着點訪問也會起作用?我是多餘的嗎?

class Email { 
    public $textBody; 
    public $attachments; 
    public $subject; 
    public $emailFolder; 

    function __construct($header) { 
     $this->head = $header; 
     $this->attachments = []; 
     preg_match('/(?<=Subject:).*/', $this->head, $match); 
     $this->subject = $match[0]; 
     if ($this->subject) { 
      $this->subject = "(No Subject)"; 
     } 
     preg_match('/(?<=From:).*/', $this->head, $match); 
     $this->fromVar = $match[0]; 
     preg_match('/(?<=To:).*/', $this->head, $match); 
     $this->toVar = $match[0]; 
     preg_match('/((?<=Date:)\w+,\s\w+\s\w+\s\w+)|((?<=Date:)\w+\s\w+\s\w+)/', $this->head, $match); 
     $this->date = $match[0]; 
     $this->date = str_replace(',', '', $this->date); 
     $this->textBody = ""; 
    } 

    function generateParsedEmailFile($textFile) { 
     if (!(file_exists("/emails"))) { 
      mkdir("/emails"); 
     } 

     $this->emailFolder = 

     $filePath = "/emails/".$this->subject.$this->date; 
     while (file_exists($filePath)) { 
      $filePath = $filePath.".1"; 
     } 
      # ......code continues 
    } 
} 
+2

在PHP中,dot是用於字符串連接的。如果你想訪問對象的方法或成員,你必須在你的實例上使用' - >',然後使用方法或公共成員的名字 – MatRt

+1

AH!所以方法也需要' - >'!很有幫助! ' - >'是否只訪問被聲明爲公共的成員? – Pinwheeler

+0

是的。 http://php.net/manual/en/language.oop5.visibility.php – ficuscr

回答

1

不,.僅用於連接字符串。 public變量(以及函數)將可以使用->運算符從「外部」直接訪問,而protectedprivate變量(和函數)需要訪問getter和setter函數。舉例如下:

class MyClass { 
    public $variableA; 
    protected $variableB; 

    public function setB($varB) { 
     $this->variableB = $varB; 
    } 

    public function getB() { 
     return $this->variableB; 
    } 
} 

$object = new MyClass(); 

$object->variableA = "new Content"; // works 
$object->variableB = "new Content"; // generates an error 
$object->setB("new Content");  // works 
+0

在上面的例子中,'$ varB'可能被命名爲'$ variableB'或者會產生一個錯誤? – Pinwheeler

+0

這不會產生錯誤。 $ this-> variableB和$ variableB是兩個不同的東西! – likeitlikeit

+1

萬歲!這意味着相當少的調試! – Pinwheeler

相關問題