PHP6 feature idea: Custom casting

The current casting support in PHP hasn’t changed since… forever?

All we have to play with is:
(string) (integer) (array) (object) (float) … any others?

A feature I would love to see is custom casting:

$product = (Product) $request['product_id'];


namespace Cast
{
    /**
     *
     * @param mixed $value
     * @return Product
     */
    function Product($value)
    {
        if (ctype_digit($value))
        {
            // find by ID via model
            return /* model->findById(value) */ ;
        }
        elseif (ctype_string($value))
        {
            // a slug ('pretty-url-for-product')
            return /* model->findBySlug(value) */ ;
        }
        elseif ($value instanceof Product)
        {
            // nothing needs changed
            return $value;
        }
        
        throw new \\InvalidArgumentException();
    }
}

Thoughts?

The idea is pretty good and I must say i like it. However, it may be harder to read 3rd-party code as we need to look at the implementation for each specific cast to understand what the hell is going on.

Variables in PHP are untyped; Only the objects they refer to have types. As such you can’t typecast a variable in php.

See: http://stackoverflow.com/questions/1147109/type-casting-for-user-defined-objects/1147377#1147377

Seems more like a syntactic shortcut for a factory, but maybe skipping the call if it’s of the right type.


$product = Product::cast($foo);
//or
$product = \\Cast\\Product($foo);
//or
$product = $foo instanceof Product ? $foo : Product::factory($foo);

looks fancy, does nothing. -1

Great idea but this can be done for classes not for functions I think.

For instance if a class is serializable then it is also unserializable without that kind of casting right now.

Which means, it is also can be casted by that.

For example;

class Product implements Serializable {…}

$product = (Product) “{…}”;

which will directly call;

$product = Product::getInstance($serialized);

Serializing and Unserializing an object automatically calls two magic methods. __sleep and __wakeup. http://php.net/manual/en/language.oop5.magic.php Making your suggestion nothing but superfluous syntax sugar.