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

贡献者指南