Re: Re: [Concept] Magic Casting
| From: | Andrey Andreev | Date: | Fri, 02 Dec 2016 15:17:14 +0000 |
| Subject: | Re: Re: [Concept] Magic Casting | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-97266@lists.php.net to get a copy of this message | ||
On Fri, Dec 2, 2016 at 4:53 PM, Alex Bowers <bowersbros@gmail.com> wrote:
>
> On 2 December 2016 at 14:46, Andrey Andreev <narf@devilix.net> wrote:
>
>> A magic method is essentially an implicit interface ...
>> The interface itself does nothing. But when it is implemented, the engine
>> will know that the class constructor is public and accepts a single
>> parameter - thus, also knowing that it could try to do a new
>> ClassName($yourParameterHere)
>>
>
> The interface would not work though, because there should be some logic in
> place too. For example, if you accept, but convert an array, or an array of
> arrays etc differently. Or would this be logic that should be placed inside
> of the constructor, and the castable will just offload to a new
> construction?
>
There's no logic in constructing differently from the same input type.
If you handle an array passed to __cast() differently to one passed to
__construct(), your design is inconsistent, to say the least.
The only reason I can think of wanting to do that is if you'd like to
magically create dependencies to pass to the constructor. For example:
class Foo {
public function __construct($scalar, Bar $bar)
{
// whatever
}
public static function __cast($var)
{
$bar = new Bar();
return new static($var, $bar);
}
}
However, that is obviously tight-coupling at least one of your
dependencies. I believe most people on the list would agree that this is
not a good thing, but even if that wasn't the case - you could still do it
in the constructor if you really wanted to:
public function __construct($scalar, Bar $bar = null)
{
if ( ! isset($bar)) {
$bar = new Bar();
}
}
Honestly, I don't see how a new method is in any way beneficial.
Cheers,
Andrey.