On 5/27/2016 11:41 AM, Lester Caine wrote:
> Now I am confused, but it's probably because I'm looking at a simple
> 
> $f->d = new DateTime( $initial );
> 
> While you are looking at
> 
> If ( isset($initial) )
> then $f->d = new DateTime( $initial );
> else $f->d = null;
> 
> While the original code would have simply been
> 
> $f->d = $initial;
> 
> And in an ideal world, because $d has been typed as DateTime this would
> magically run 'new DateTime($initial)' which is where I am stumbling
> because *I* simply look at '?DateTime $d' as creating a DateTime object
> where in fact $d is a different type of object which will then hold the
> link to the real one. I am still looking for $d to be an object I can do
> all of the checks on that are provided by int or DateTime as appropriate
> ... the object needs to exist before the 'new' in order to know if you
> need the first or second type of $initial code ... or we make typed
> properties only work one way or the other?
> 

PHP does not automagically instantiate the DateTime object for you, this
is still your responsibility. The type hint on the property only
restricts what you are allowed to assign to the property, nothing else.

It is true that PHP will coerce the value automatically if you are in
weak mode but this is only true for scalar values and nothing else. Also
note that you might not want that while working with a database because
PHP might destroy your UNSIGNED BIGINTs without you noticing.

  class O {
    public ?DateTime $d;
  }

  if (isset($row['d'])) {
    $o->d = new DateTime($row['d']);
  }

No need to assign null since it already is null by default and the
nullable hint will not result in any errors upon accessing it.

PS: The UNSIGNED BIGINT thing is one of the reasons why I want
intersection and union types so that we can do the following:

  class O {
    private int|string $id;
  }

And leave it to a more intelligent system to determine whether this can
be safely converted to an int or not (e.g. MySQLi).

-- 
Richard "Fleshgrinder" Fussenegger

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to