Clarifications on settype() behaviour wrt coercion and failure
Nobody has claimed this yet.
- Dominant language
- XML
- Stars
- 596
- Forks
- 890
- Avg merge
- 1d 15h
- Merged PRs (30d)
- 55
Description
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).
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the settype() documentation entry and review ext/standard/tests/general_functions/settype_typed_property.phpt for the typed-property behavior described here. Update the documentation to state the actual coercion behavior and that failures throw TypeError rather than returning false, then verify the examples and return-value wording are consistent.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 50/100