Type casting for user defined objects

前端 未结 11 1556
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 01:35

Just like we do with __ToString, is there a way to define a method for casting?

$obj = (MyClass) $another_class_obj;
11条回答
  •  情歌与酒
    2020-11-29 01:48

    I think you mean Type-Hinting.

    As of PHP 7.2, you can type-hint arguments in functions:

    function something(Some_Object $argument) {...} # Type-hinting object on function arguments works on PHP 7.2+
    

    But you can't type-hint it like this:

    (Some_Object) $variable = get_some_object($id); # This does not work, even in PHP 7.2
    

    The alternative for type-hinting objects while it isn't implemented officialy in PHP, is:

    $variable = get_some_object($id); # We expect Some_Object to return
    is_a($argument, 'Some_Object') || die('get_some_object() function didn't return Some_Object');
    

提交回复
热议问题