Press "Enter" to skip to content

深入理解PHP原理之Opcodes

最近要给Yahoo的同事们做一个关于PHP和Apache处理请求的内部机制的讲座,刚好写了些关于Opcodes的文字,就发上来了,这个文章基于 Sara Golemon大师的《Understanding OPcode》

Opcode是一种PHP脚本编译后的中间语言,就像Java的ByteCode,或者.NET的MSL,举个例子,比如你写下了如下的PHP代码:

 <?php
   echo "Hello World";
   $a = 1 + 1;
   echo $a;
?>

PHP执行这段代码会经过如下4个步骤(确切的来说,应该是PHP的语言引擎Zend)

1.Scanning(Lexing) ,将PHP代码转换为语言片段(Tokens)
2.Parsing, 将Tokens转换成简单而有意义的表达式
3.Compilation, 将表达式编译成Opocdes
4.Execution, 顺次执行Opcodes,每次一条,从而实现PHP脚本的功能。

题外话:现在有的Cache比如APC,可以使得PHP缓存住Opcodes,这样,每次有请求来临的时候,就不需要重复执行前面3步,从而能大幅的提高PHP的执行速度。

那什么是Lexing? 学过编译原理的同学都应该对编译原理中的词法分析步骤有所了解,Lex就是一个词法分析的依据表。 Zend/zend_language_scanner.c会根据Zend/zend_language_scanner.l(Lex文件),来输入的 PHP代码进行词法分析,从而得到一个一个的“词”,PHP4.2开始提供了一个函数叫token_get_all,这个函数就可以讲一段PHP代码 Scanning成Tokens;
如果用这个函数处理我们开头提到的PHP代码,将会得到如下结果:

Array
(
    [0] => Array
        (
           [0] => 367
           [1] =>  Array
        (
            [0] => 316
            [1] => echo
        )
    [2] => Array
        (
            [0] => 370
            [1] =>
        )
    [3] => Array
        (
            [0] => 315
            [1] => "Hello World"
        )
    [4] => ;
    [5] => Array
        (
            [0] => 370
            [1] =>
        )
    [6] => =
    [7] => Array
        (
            [0] => 370
            [1] =>
        )
    [8] => Array
        (
            [0] => 305
            [1] => 1
        )
    [9] => Array
        (
            [0] => 370
            [1] =>
        )
    [10] => +
    [11] => Array
        (
            [0] => 370
            [1] =>
        )
    [12] => Array
        (
            [0] => 305
            [1] => 1
        )
    [13] => ;
    [14] => Array
        (
            [0] => 370
            [1] =>
        )
    [15] => Array
        (
            [0] => 316
            [1] => echo
        )
    [16] => Array
        (
            [0] => 370
            [1] =>
        )
    [17] => ;
)

分析这个返回结果我们可以发现,源码中的字符串,字符,空格,都会原样返回。每个源代码中的字符,都会出现在相应的顺序处。而,其他的比如标签,操作符,语句,都会被转换成一个包含俩部分的Array: Token ID (也就是在Zend内部的改Token的对应码,比如,T_ECHO,T_STRING),和源码中的原来的内容。
接下来,就是Parsing阶段了,Parsing首先会丢弃Tokens Array中的多于的空格,然后将剩余的Tokens转换成一个一个的简单的表达式

1.echo a constant string
2.add two numbers together
3.store the result of the prior expression to a variable
4.echo a variable

然后就改Compilation阶段了,它会把Tokens编译成一个个op_array, 每个op_arrayd包含如下5个部分:

1.Opcode数字的标识,指明了每个op_array的操作类型,比如add , echo
2.结果       存放Opcode结果
3.操作数1  给Opcode的操作数
4.操作数2
5.扩展值   1个整形用来区别被重载的操作符

比如,我们的PHP代码会被Parsing成:

* ZEND_ECHO     'Hello World'
* ZEND_ADD       ~0 1 1
* ZEND_ASSIGN  !0 ~0
* ZEND_ECHO     !0

呵呵,你可能会问了,我们的$a去那里了?

恩,这个要介绍操作数了,每个操作数都是由以下俩个部分组成:

a)op_type : 为IS_CONST, IS_TMP_VAR, IS_VAR, IS_UNUSED, or IS_CV

b)u,一个联合体,根据op_type的不同,分别用不同的类型保存了这个操作数的值(const)或者左值(var)

而对于var来说,每个var也不一样

IS_TMP_VAR, 顾名思义,这个是一个临时变量,保存一些op_array的结果,以便接下来的op_array使用,这种的操作数的u保存着一个指向变量表的一个句柄(整数),这种操作数一般用~开头,比如~0,表示变量表的0号未知的临时变量

IS_VAR 这种就是我们一般意义上的变量了,他们以$开头表示

IS_CV 表示ZE2.1/PHP5.1以后的编译器使用的一种cache机制,这种变量保存着被它引用的变量的地址,当一个变量第一次被引用的时候,就会被CV起来,以后对这个变量的引用就不需要再次去查找active符号表了,CV变量以!开头表示。

这么看来,我们的$a被优化成!0了。

76 Comments

  1. pangee
    pangee 2012-09-28

    好文再读。

    话说鸟哥08年就这么牛逼了~ oh ~ 08年我还在大学里谈恋爱、打CS呢……!

  2. FightingMan
    FightingMan 2012-04-22

    看鸟哥的文章,心情始终那么舒畅婉如久旱逢甘霖

  3. […] 在阅读这篇文章的时候,发现命令都不能使,遂有了这篇文章。。。。 三个工具分别是: Tokenizer, Parseket, Vulcan Logic Disassembler. (1)phpsize找不到怎么办? sudo apt-get install php5-dev (2) install Parsekit sudo pecl install Parsekit 修改php.ini的so加载文件,加入parsekit.so (3) install Vulcan Logic Dumper You can get the source from SVN: svn co svn://svn.xdebug.org/svn/php/vld/trunk vld Here are the instructions to get it to work: cd into the newly checked-out directory. Create the configure script: phpize Now run “./configure” followed by “make install”. That’s it, if you now run PHP from the command line and add the -dvld.active=1 parameter VLD will spit out the opcodes: 修改php.ini的so加载文件,加入vld.so […]

  4. Nicole Thompsen
    Nicole Thompsen 2010-09-01

    These drivers may sometimes come with additional functionality unavailable in worldwide drivers or other drivers not predestined for that special archetypal. If you find modern movie online, choosing the DVDs to rent is aided rolex replica watches nit-picking and patron ratings and reviews. Even a situate of horror movies, romantic movies, battle swiss rolex replica watches and comedy movies are to be had in cheap rolex replicas promote. Episode 48 (Fairy Tales Can Come True) Air Date: 10-25-1984. The new swiss rolex replicas, you will perhaps be tempted to get a shelf replica rolex watch entertainment meeting point with your TV. The new rolex replicas new fake rolex wactch the years outdo, Bailey must contract with his own relations problems, his discontented dreams, and fake rolex burdens of the cheap rolex replicas Depression. Defeated, you have resigned yourself rolex replicas the fact that you replica rolex watch pass on without interminably unlocking the sly of how to assigning DVD into iPod. Episode 39 (Officers Only) cheap rolex replicas Date: 12-22-1973. One key swiss replica rolex of this function swiss rolex replicas that it is used to retail copyrighted things. The new fake rolex wactch nine successful swiss replica rolex to its honor, The X-Files is one of fake rolex rolex replica watches-running sci-fi series in television history?. Using a DVD Collection Database fake rolex wactch Ratings. The new swiss rolex replica watches new rolex replicas swiss rolex replicas the scientific component of the crimson, depressed and bottle green components in swiss replica rolex colour rolex replica watches. By informative the tale of world fame and internationally respected artist Big Pun, director Vlad Yudin brings us the exclusive real-life look at swiss replica rolex artist who changed the hip-hoedown fake rolex wactch and tap game forever. The Felicity ( fake rolex wactch new rolex replicas 3) DVD features a number of exciting episodes including the season premiere “The Christening” in which swiss rolex replicas learns from Javier that a man is giving away his furniture before heartbreaking fake rolex wactch another utter. avi,.

  5. Lousesi minii
    Lousesi minii 2010-08-23

    Such was his lot in life, resigned without end to powerful time only by looking at the fake rolex watch demonstrate clocks on times rectangle. Janice couldn�t judge her eyes! The prevalent trend of black watch over dials was in progress in Rolex. What they in reality give is a stone crystal. There are as much as necessary replica Rolex watches outmoded here in favor of them to like. Are you picture a six replica rolex salary, compelling a Limousine and breathing in a hall? That is, the universe hold to have been more compressed formerly and rolex replicas were harder to happen near. A dressed indisputable Rolex watchband tin approach in a duo incarnations. � Rolex replicas made in other Asian countries (but Japan and Korea);. Certawearingly, Rolex replica rolex watches don�t include fake gold plating�. There are loads of Rolex model watches which exhibit stickers which display the logo of Rolex. The editorial discussion on the subject of why Rolex is a widely held big name in the world of watchmakers? Brand new for the year 2002, the company has launched micro-print a painstaking “tiara” sign into the crystal for the genuine Rolex watch, at the 6 o’clock scene. Only those watches arrive to the market which has lucratively accepted those investigate and others are sent ago. Up to this era, Rolex is banish a privately-owned one, and never went community to amicable its set to other shareholders.

  6. kikisu minii
    kikisu minii 2010-08-17

    Features & Performance: One of my choice features on the Sony DCR-DVD650 DVD Handycam camcorder is the erstwhile fashioned ‘optical viewfinder’ that is totally uncommon in camcorders currently. The new rolex replicas family are storing memories and movies on DVD which can keep on everyplace from 25 years to 250 years. It mounts going on a vehicle’s ceiling, typically flanked by the frontage and backside seats. How to orderly DVDs is cute easy if you know the individual aids to use and how to use them fittingly. The team that was sent to track becomes the hunted and are no complement for alien technology, but the make is highly-flavored with one of them. Episode 106 (The Sound of Children) Air Date: 02-05-1979. This format too uses the wretched laser, the alteration essence the higher compression of the video onslaught. Once you have your distributors in command you need to make your mind up how you want to persuade somebody to buy you goods. Corporal do well Klinger (Jamie Farr) provides comic relief with his first attempts to acquire a discharge by dressing in women’s clothing, and Father Francis Mulcahy (William Christopher) adds give flavor to to a diverse cast of characters. This income that you need to have advantage product expertise so that you can actually rise the product you are buying. Step #6 – Cleaning the Laser Pickup – Now that you have swiss rolex replica watches access to the laser jump back in, use a cotton mop and several isopropyl alcohol and gently wipe the lens. Lets play it, children get bored easily and to rolex replica watch your everyday jobs and pouring time turn easier, a Player is the way to go. Episode 40 (Indian Summer) Air Date: 10-27-1999.

  7. kikisu minii
    kikisu minii 2010-08-17

    DVD players immediately can be made of extremely economical material, which brings us to our number one advantage. Once it’s ended, you should see a new file in the rawdump folder, an ISO file, with the same term as anything game you unoriginal. So how preserve this befall achievable? Episode 48 (Don’t Bug the Mosquitoes) Air Date: 12-09-1965. Finding a DVD fake rolex iPod converter with the aim of has a early conversion esteem is a necessity. Episode 26 (Angels on Ice: Part 2) Air Date: 09-21-1977. Or would you noticeably be skilled to pick out your specific music? When I pioneer in progress funing I was amazed at how I was adept to play songs that I loved within a few days. Along with the headphones, this a great way to keep your little tyke contentedly unavailable for the period of rolex replica watch long rolex replicas stumble. Downloads are fast, easy to install and have user interfaces that are friendly.

  8. […] 了解opcode(深入理解PHP原理之Opcodes的同学都知道, 在PHP5.3以前, 每一个可独立运行的op array(文件, 函数, 方法)的最后一条opcode都是ZEND_HANDLE_EXCEPTION, 而这个opcode是做什么用的呢? […]

  9. […] 了解opcode(深入理解PHP原理之Opcodes的同学都知道, 在PHP5.3以前, 每一个可独立运行的op array(文件, 函数, 方法)的最后一条opcode都是ZEND_HANDLE_EXCEPTION, 而这个opcode是做什么用的呢? […]

  10. savannah
    savannah 2010-06-30

    Keep in mind that many resources are available fake tissot watches milgauss watches replica cartier declaration watches tag heuer slr watches professional diver will have a watch that will be water movado royal oak offshore 27 stood for the movements diameter in millimeters and C12 rolex fake worldwide as every woman knows that diamonds are a girls twenty 4 watches replica watches insurance policies and exceptional multi-year warranties. a lange and sohne watches more and more appreciated by celebrities common people fake patek philippe twenty 4 watches changes came more unique watches but most of replica watches watch imitations the company stays innovative omega olympic collection However since the 310 is going to become a premier replica watches Golf Master has been developed as a mechanical swiss rolex replica bell and ross watches of the 21st century The selfwinding movement fake panerai watches Eco-Drive watch draws watch at all times from natural

  11. jacky
    jacky 2010-06-25

    昨天我正好在看
    《Pro PHP Patterns Frameworks Testing and More》
    里面就谈到了lexing:
    While PHP is not a compiled language, it resembles compiled languages in that PHP code
    is converted into a binary format before actually being executed.

    This transformation from programming language
    to executable code is called
    >>>lexing
    because it transforms the lexical structure of PHP code into
    >>>opcodes(numeric representation of PHP language elements).

    维基百科上对于opcode(operation code)的解释:
    is the portion of a machine language instruction that specifies the operation
    to be performed.

  12. Breitling
    Breitling 2010-06-25

    With so many games streaming data from the HAZEL on the fly. The methodology for the tests was remarkably straight for ward first from HAZEL DVD, then from hard disk. As the opportunity to install to HAZEL DVD COLLECTION is obviously a compelling argument for upgrading the hard disk.HERE’S LUCY

  13. nanninghechi
    nanninghechi 2010-04-21

    Jazzy clothes go well with relations of Louis Vuitton having unadorned devise. You should to respect your style when choosing your right family of london jewelry. Nevertheless it is a big inquiry for many women to highlight your personalities. For command, long family Louis Vuitton handbags will give the illusion of piece, so a ribbon with one effective important touch a little above the bust line will look great Because of this, the charms which could exactly pageant their purity and innocence. In the decoration of the proceed. Therefore, You will never be analogous to your dresses, age, career, complexion and with wheat influence would look better by bearing jewels that are not so vivid, for example the pearls or silver decorated family Louis Vuitton classic charms . Ladies with dull wrecked are also good array for them. Nothing will be more right than these brilliant jewels for these fleshy ladies who will be looked sporting by taxing brilliant relations of Louis Vuitton wholesale. Girls taxing refined dresses should neither be disquiet about that will lengthen the charms are proper for your face form nor completely different from your face affect. Besides, agate and tawny are correct for jewels that your causal dresses are too ordinary if the relations of london are well matched with clothes. Some blush. Hope to help you! Make reliable the look of your face. With an around face you want to look for them. You know what! Women’s Louis Vuitton box is bottomless, just like women’s require for new jewelries. On you. Hairstyle plays an important part In deference that sole judgment and personal qualities will be displayed if you game them with a well-intended trinkets with Some suggestions on choosing and matching jewelries are as follow. Keep in mentality, the character of your Louis Vuitton jewelries should game small and elegant links of london heart which are easy, small, and other aspects to wish jewelries right.

  14. Ellen22
    Ellen22 2010-01-26

    Wow, hot topic related to this good topic. Could please tell me how long period of time that will take? Just because I want to finish the dissertation idea or probably it would be better to determine the thesis writing. Thnx.

  15. wan
    wan 2009-08-18

    好文章,已认真阅读,请问为什么每次生成的 opcodes 的最后总是会有这么一条指令: * ZEND_HANDLE_EXCEPTION , 请指点。谢谢

  16. Anonymous
    Anonymous 2008-10-19

    左手源码,右手诗,吾甚向往之。。。。。。

  17. 熊林
    熊林 2008-10-10

    来看看,不错

  18. highjade
    highjade 2008-10-10

    学习。

  19. xiaoj
    xiaoj 2008-10-05

    PHP Opcode Dumper,这个工具可以查看到编译后的opcodes

  20. 雪候鸟
    雪候鸟 2008-09-11

    to chen, 可以通过vld扩展获取.
    关于vld的原理,我记得我以前的文章介绍过.

  21. Anonymous
    Anonymous 2008-08-31

    以后多向你老人家学习

  22. chen
    chen 2008-08-27

    本人学艺不精,看了你的文章后有很多疑问,这个php的opcode怎么能够得到啊?能具体说说吗?

  23. […] 你所编写的脚本,最终都会被转换成C代码来执行。 这个和我在以前文章中(深入理解PHP原理之Opcodes)介绍的opcode并不冲突, […]

Leave a Reply

Your email address will not be published. Required fields are marked *