Re: [RFC][Vote] Typed Properties
| From: | Fleshgrinder | Date: | Thu, 26 May 2016 16:48:20 +0000 |
| Subject: | Re: [RFC][Vote] Typed Properties | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-93574@lists.php.net to get a copy of this message | ||
On 5/26/2016 6:40 PM, Tom Worster wrote:
> On 5/26/16, 12:30 PM, "Fleshgrinder" <php@fleshgrinder.com> wrote:
>
>> The problem is a completely different one, how should the following code
>> behave?
>>
>> class A {
>>
>> public int $x;
>>
>> }
>>
>> (new A)->x;
>>
>> The property has no value assigned but it is being accessed. The current
>> PHP behavior is to simply initialize it with null. But this is
>> impossible according to the type definition.
>>
>> There are not many ways to handle this. I think we already had all of
>> them proposed:
>>
>> 0. Fatal error after __construct was called.
>> 1. Fatal error and abort.
>> 2. Initialize with appropriate type.
>> 3. Initialize with null.
>
> Under another 5th option, the problem you state does not arise. Disallow
> "public int $x;". Under this option you may declare $x with type int and
> an initial value or you may declare $x without type but you may not
> declare $x with type (nullable or not) and undefined initial value.
>
> Tom
>
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';
}
Not cool. :(
--
Richard "Fleshgrinder" Fussenegger
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc