Вопрос

I just want to make sure I'm doing this correctly. I'm a little confused between $this->parameter, $parameter and public $parameter

Here's an example of what I'm doing. I want anything that's declared as public to be able to be accessed with the $instance->parameter method. Does this mean that dot accessing will also work? Am I being redundant?

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
    }
}
Это было полезно?

Решение

No, the . is only for concatenating strings. public variables (as well as functions) will be accessible directly from "outside" using the -> operator, while protected and private variables (and functions) will need getter and setter functions to be accessed. An example would look like this:

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top