Search code examples
phpnulloperator-keywordphp-8

How does null safe operator works in php 8?


PHP introduced null operator in PHP8. What is the benefit of using Null operator. And how does it work? Will be delightful in anyone enlighten my knowledge.


Solution

  • What it does is surely explained in the blog post you found it mentioned in.

    How it works is best explained by a simple bytecode dump:

     L3    #0     JMP_NULL                $null                J5                   @1
     L3    #1     FETCH_OBJ_R             $null                "optional"           ~0
     L3    #2     JMP_NULL                ~0                   J5                   @1
     L3    #3     INIT_METHOD_CALL        ~0                   "maybenull"  
     L3    #4     DO_FCALL  
     L4    #5     RETURN<-1>              1   
    

    Any occurence of ?-> is represented by an attribute fetch or method call, but preceded with JMP_NULL, that would simply skip the remainder of the expression.