php/doc-en

Clarifications on settype() behaviour wrt coercion and failure

オープン

#2,677 opened on 2023/08/11

 (2 件のコメント) (0 件のリアクション) (0 人の担当者)XML (882 件のフォーク)auto 404
Category: EngineStatus: Verifiedgood first issue

Repository metrics

Stars
 (596 個のスター)
PR merge metrics
 (平均マージ 99d 23h) (30d で 90 merged PRs)

説明

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).

コントリビューターガイド