Type casting for user defined objects

前端 未结 11 1583
没有蜡笔的小新
没有蜡笔的小新 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 02:05

    I mainly need type casting to enable intellisense - so I just create a type cast helper:

    function castToTest($val): Test
    {
        return $val;
    }
    $test = castToTest(require("someFile.php"));
    

    Returning from a file is kind of ugly and does not allow for type hinting, so this is a perfect example of how you can achieve intellisense by using a type cast helper.

提交回复
热议问题