php/doc-en

Clarifications on settype() behaviour wrt coercion and failure

Aperta

#2677 aperta il 11 ago 2023

 (2 commenti) (0 reazioni) (0 assegnatari)XML (882 fork)auto 404
Category: EngineStatus: Verifiedgood first issue

Metriche repository

Star
 (596 stelle)
Metriche merge PR
 (Merge medio 99g 23h) (90 PR mergiate in 30 g)

Descrizione

The following code:

<?php

class Foo {
    public int $value = 123;
}

$foo = new Foo;
$ref = &$foo->value;

var_dump(settype($ref, "string"));
var_dump($ref);
var_dump($foo->value);

Resulted in this output:

bool(true)
int(123)
int(123)

But I expected this output instead:

bool(false)
int(123)
int(123)

Well either bool(false) or a type error, as its supposed to return false when setting the type fails according to the documentation. Although that's probably inaccurate, as the following code:

<?php

class Foo {
    public int $value = 123;
}

$foo = new Foo;
$ref = &$foo->value;

var_dump(settype($ref, "null"));
var_dump($ref);
var_dump($foo->value);

Results in: Fatal error: Uncaught TypeError: Cannot assign null to reference held by property Foo::$value of type int. And the code for settype can only return true as far as I can see.

So there's two documentation issues:

  • The function can only return true. On error it throws TypeErrors
  • It coerces in non-strict mode. That's why the string assignment in the first eaxmple "works". (This is also tested as a variant in ext/standard/tests/general_functions/settype_typed_property.phpt, but I didn't know this at first, until I tried fixing the behaviour I thought was a bug).

Guida contributor