PHP自增自减

WBOY
Release: 2016-06-23 14:33:37
Original
2163 people have browsed it

写出一下php段的输出结果:

<?php $count=5;function get_count(){    static $count=0;    return $count++;}echo $count;++$count;echo get_count();echo get_count();?>
Copy after login

答案为:501

主要涉及到两个知识点:

1.php变量的作用域;

2.自增/自减变量;

面试人对 “php变量的作用域” 理解挺到位,但在 “自增/自减变量” 上有些把握不准。现复习如下,以供参考:

自增/减分为前置和后置,这涉及到一个先后顺序:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php   $a = 3;   echo ++$a; //前置型,先自增再输出,结果为4,此时$a为4   $b = 3;   echo $b++; //后置型,先输出3,再自增为4,此时$b为4 ?>
Copy after login

 

 问题:若$i=2,求表达式($i++)*($i++)*($i++)的值,并求$i的值

 答案:($i++)*($i++)*($i++)结果为24,$i为5

 

 分析:先看计算顺序,发现有括号则先算括号里面的,先取$i的值2为($i++)的值,然后$i自加为3;  [此时($i++)左=2,$i=3]

            再算括号中,先取此时的$i的值3为($i++)的值,然后$i再自加为4;[此时($i++)中=3,$i=4]

            后算括号右,先取此时的$i的值4作为($i++)的值,然后$i再自加为5

            最后做乘法运算,即2*3*4=24          $i=5

Related labels:
source:php.cn
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