Home > Backend Development > PHP Tutorial > PHP analysis on $i++ and ++$i

PHP analysis on $i++ and ++$i

巴扎黑
Release: 2016-11-21 15:10:59
Original
1544 people have browsed it

This article uses the VLD tool to analyze the opcode of php to explain the reason. First, post the picture

T1.php code

$i = 1;

$i+$i++;

Vld code

number of ops: 5

compiled vars: !0 = $i

line # * op fetch ext return operands

------------------------- -------------------------------------------------- --------

2 0 > ASSIGN                                                                                                                                 ~2                                                                                      gt ; RETURN                                                                                     4

path #1: 0,

T2.php code

$i = 1;

$i+$i+$i++

Vld2 code

number of ops: 6

compiled vars: !0 = $i

line # * op fetch ext return operands

--------- -------------------------------------------------- -----------------------

2 0 > ASSIGN                                                                                                                                                                                                                          

2 POST_INC 3 ADD                                                                                                ~3

4 5 > RETURN                                            2- 4; sop: 0 ; eop: 5

path #1: 0,

Let’s compare the two pictures 2 and 4, and you can know why the results will surprise you

First analyze the execution results of 1 and 2

First $ i is assigned a value of 1, $i++ is incremented, the result 1 is copied to the temporary variable ~1 ($i), and then $i is incremented to 2, that is! 0=2, of course the final result ~2 = ~1+! 0 ===3;

Let’s analyze 3,4

First, $i is assigned a value of 1, then $i+$i = !0+!0 == ~1 == 2, then $i++ is incremented, and The result 1 is copied to the temporary variable ~2 ($i), and the final result ~1+~2 == 2+1 ===3;

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template