On 26/05/2016 20:33, Lester Caine wrote:
If I am creating an object which is a 'person' for which I actually want
to ensure I have valid dates for birth, marriage and death and an
integer 'no of siblings' then I have a set of 'typed' properties.
Initially the object is not initialized ... no person found in the
database ... so null values for every property in the object. When I
search and find a match, then I may get someone who is 'alive' so the
death property remains null. Currently one can not use DateTime
variables to do any of this as they have already defined their own
alternative to null by blocking it. So in this case it is pointless
trying to create any 'can be null' flag? Class variables are simply not
handling the problem consistently so one has to jump through hoops to
get back what used to be a simple null initialised set of properties?
The current proposal (or the one which I am advocating) for that is that
you would have something like the following:
class Person {
public \DateTime $birth;
public ?\DateTime $marriage;
public ?\DateTime $death;
public int $numSiblings;
}
Creating an object would leave it in an invalid state:
$me = new Person;
// accessing $me->birth or $me->numSiblings is an error in this state,
because defaulting to NULL would violate their type constraint
// accessing $me->marriage or $me->death returns NULL (because they
allow nulls) but raises E_NOTICE
Now you can initialise the mandatory fields:
$me->birth = new \DateTime($db_record['birth_date']);
$me->marriage = new \DateTime($db_record['marriage_date']);
$me->death = new \DateTime($db_record['death_date']);
$me->numSiblings = $db_record['num_siblings'];
// all properties can now be safely accessed
// $me->marriage and $me->death may still be null, as indicated by the
"?" in their type spec
// $me->birth is guaranteed to be a \DateTime object
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php