On 5/26/2016 7:00 PM, Tom Worster wrote: > On 5/26/16, 12:48 PM, "Fleshgrinder" <p...@fleshgrinder.com> wrote: >> This would be a valid approach too, yes. I personally would be against >> it because I do not want to initialize all my properties. >> >> class A { >> >> private int $x; >> >> public function getX() { >> if (empty($this->x)) { >> $this->x = 42; >> } >> return $this->x; >> } >> >> } >> >> This would not yield an E_NOTICE because both isset() and empty() never >> do. This allows the attentive programmers to keep up there coding >> practices without the necessity to assign meaningless values everywhere. >> >> class A { >> >> /** -1 is invalid */ >> public int $x = -1; >> >> /** 'INVALID' is invalid but empty string is allowed */ >> public string $s = 'INVALID'; >> >> /** Null byte is invalid but anything else is valid */ >> public string $welcome_to_the_c_world = '\0'; >> >> } > > If you want that kind of thing, you can do it the old PHP way like this > > class A { > private ?int $x = null; > ... >
Doing that defeats the whole purpose of typed properties in my opinion. I want to be sure that nobody can assign null to this property and only allow it to be null until I initialize it myself. class A { private int $x; private function getX() { if (empty($this->x)) { $this->x = 42; } return $this->x; } public function doSomething() { // lots of code ... $_ = $__ * $this->x; // lots of code ... } } This would emit an E_NOTICE (and possibly end up in an error due to null) and the developer of the doSomething() method will notice that she should call getX() instead. This would not be the case with private ?int $x. :( -- Richard "Fleshgrinder" Fussenegger
signature.asc
Description: OpenPGP digital signature