Class cast
| From: | David Rodrigues | Date: | Wed, 25 Mar 2020 16:51:31 +0000 |
| Subject: | Class cast | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-109302@lists.php.net to get a copy of this message | ||
Currently PHP supports generic castings like (string), (int), ... maybe is
time to allow class castings like (ToClass) $fromObject?
I think that it could be useful to converts to another kind of structure,
or even to reduce object type.
For instance:
---
1. Converting from A to B:
$a = 123;
$b = (Number) $a; // $b is now instanceof Number
A instanceof Number will created based on $a value.
---
2. Reduce object type (I don't know the technical term):
class A {}
class B extends A {}
$b = new B;
$a = (A) $b;
$a still is $b, but with "limited" access to A methods and properties.
---
To make possible custom some kind of castings, I suggests a new magic
method __cast($value).
class Number {
...
function __cast($value) {
if (is_int($value) || is_float($value)) return new static($value);
throw new TypeError();
}
}
Just to talk.
Atenciosamente,
David Rodrigues