Implicit Type Conversion for PHP Classes?

前端 未结 7 1134
轻奢々
轻奢々 2021-01-25 06:16

Is there a way to tell the php complier that I want a specific implicit conversion from one type to another?

A simple example:

class Integer
{
  public $         


        
7条回答
  •  悲哀的现实
    2021-01-25 06:50

    This question is very old, but I would like to give a solution. This behaviour is called boxing which can be done in PHP, but the inverse of this, unboxing see:

    function a(int $a){...}
    
    a(new Integer(1));
    

    is not possible currently. If you want a framework which offers you this and even more, look at the BlazeFramework which has such wrapper classes.

    Operation overloading does not work either in php. The implementation is maybe a bit too much to write, but I give you a hint! PHP calls the callback set with set_error_handler() with the error level E_RECOVERABLE_ERROR and debug_backtrace() delivers information about the function/method call.

    If you don't get that, look at the implementation of the method blaze\lang\System#systemErrorHandler(), but possibly it is better to just use the framework if you want more of such features.

提交回复
热议问题