Type casting for user defined objects

前端 未结 11 1581
没有蜡笔的小新
没有蜡笔的小新 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 do not believe there is a overloading operator in PHP to handle that, however:

    _number = $obj;
        } else if ($obj instanceOf MyNumberClass){
          /// some other type of casting
        }
        return $new;
      }
    }
    
    $test = MyClass::castFrom(123123);
    var_dump($test);
    

    Is one way to handle it.

提交回复
热议问题