I'm not sure if this is a bug, an oversight, or something that is known and deemed not-worth-fixing, so I thought I would ask here first.

Consider the SPL_Types extension. This extension introduces some classes that override assignment in order to do some type-checked autoboxing:

$int = new SplInt;
$int = 5;               
//$int is not overwritten with scalar '5', but is now SplInt(5).

$int = 'foo';
//throws UnexpectedValueException: Value not an integer

That is a pretty neat thing. However, I would see the primary use-case for this as the following:

function foo(SplInt $int)
{
        //some code
}

foo(5); 


Unfortunately, this produces "Catchable fatal error: argument 1 passed to foo() must be an instance of SplInt, integer given". This, however, works:

$int = new SplInt;
$int = 5;
foo($int);

Does it seem like a good idea for the type checking mechanism for type hinted parameters to check whether the hinted class has overridden assignment, and if so, delegate the type checking to that mechanism? For example,

foo('bar');

would yield 'UnexpectedValueException: Value not an integer', rather than the catchable fatal error associated with the type hinted parameter.

Or, perhaps there is something that the extension itself could be doing to make this happen? Or, perhaps this intentionally does not happen?

I know that genuine scalar type hints are kinda-sorta-maybe on the table for a future version, but as of right now using the SPL Types to emulate that in a performant way would be pretty neat.


Thanks,
Jeremy

P.S. - As a side note - I wonder whether it would be possible to make accessible from userspace the functionality that SPL_Types uses to override assignment? For example, you could have an __assign($value) magic method that, if present, would be invoked when attempting to assign a value to an existing object:

class Foo
{
        public function __assign($value)
        {
                echo $value;
        }
}

$foo = new Foo;
$foo = 'foobar';        //outputs foobar
echo ($foo instanceof Foo);     //output 1

That's not something I'm really requesting - just an interesting thought. I'm sure that operator overloading has been brought up and shot down before, and that functionality is dangerously close to such. But yeah.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to