php/doc-en

Clarifications on settype() behaviour wrt coercion and failure

開放

#2,677 建立於 2023年8月11日

 (2 則留言) (0 個反應) (0 位負責人)XML (882 個分叉)auto 404
Category: EngineStatus: Verifiedgood first issue

倉庫指標

星標
 (596 顆星)
PR 合併指標
 (平均合併 99天 23小時) (30 天內合併 90 個 PR)

描述

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

貢獻者指南