PHP object-oriented interpreter Mode

Source: Internet
Author: User

PHP object-oriented interpreter Mode

I recently read "in-depth PHP object-oriented model and Practice". After learning the content in the book, I instantly felt that I was a little tall! It's actually a dish B. I believe there will also be new friends reading this book (I am also a newbie). I personally want to share and exchange my learning experiences on the content that I personally think is more difficult in this book, 1. I hope to consolidate and deepen my understanding of what I have learned. 2. I hope to help new users who are interested in this article.

This part of content has been read several times and followed several times. It is estimated that the function to be implemented in this article is probably to enter some content on the web page, then, the system will reply after parsing through the background program (the feeling is nonsense ). For example, in the front-end web page input box, enter:

$input = "4";$input equals "4" or $input equals "four";

After the submission, the system will reply the result similar to "condition is true" or "condition is not true" (a bit similar to writing code directly at the front end and running it, a result will be returned after parsing in the background. Although the original book did not explain the process of entering the entire front-end to the background parsing, I guess this background parsing should also have a process of extracting keywords similar to the above two lines of code using regular expressions)

Although the above two lines of code were invented by the author, it is not difficult to understand the literal meaning. The first line is to define a variable and assign values, the second line is to make a judgment on the variable (the variable is equal to 4 or equal to four ).

Not much nonsense. Let's take a look at the classes defined in this mode (for the class diagram, see the original article ):

1. interpreterContext is like a container.It is mainly used to store and obtain the values to be compared and the comparison results, such as 4, four in the above Code, and the comparison results are "true" or "false ", the storage format is array, which is the class attribute $ expressionstore. The Code is as follows:

Class InterpreterContext {private $ expressionstore = array (); // store the comparison value and result function replace (Expression $ exp, $ value) {// set the value $ this-> expressionstore [$ exp-> getKey ()] = $ value;} function lookup (Expression $ exp) {// obtain the value return $ this-> expressionstore [$ exp-> getKey ()];}

This class is like a tool for other classes (it has no inheritance, combination, or aggregation relationship with other classes ).

2. Expression is an abstract class of an Expression. It defines the Abstract METHODS interpret () and the method getKey ()

The Code is as follows:

Abstract class Expression {private static $ keycount = 0; // private $ key for counting; // store a unique value // It stores the data obtained from the foreground in the InterpreterContext class, when you see the following content, you will find that the inherited class calls the replace () method of the InterpreterContext class abstract function interpret (InterpreterContext $ context); // gets a unique value function getKey () {if (! Isset ($ this-> key) {self: $ keycount ++; $ this-> key = self: $ keycount;} return $ this-> key ;}}

The classes to be discussed below will all inherit this class, and they and OperatorExpression (operator expression abstract class) are a combination relationship, that is to say, OperatorExpression can contain all subclasses that inherit Expression during initialization (this is also the book's emphasis on interface-oriented programming. This Expression is an interface, which can be used to achieve polymorphism, I don't know what I said when I installed B! For details, refer to the class diagram of the original book)

3. LiteralExpression text expression class, which is used to save a string to the small container of InterpreterContext as an index array. For example, save 4 or four in the first two sentences of your own code.

The Code is as follows:

Class LiteralExpression extends Expression {private $ value; function _ construct ($ value) {// input the value to be saved during initialization $ this-> value = $ value ;} function interpret (InterpreterContext $ context) {// call the replace () of the InterpreterContext class to save $ value to the small container of InterpreterContext $ context-> replace ($ this, $ this-> value );}}

Iv. VariableExpression: Variable expression class. It is the same as the above class, except that the data will be saved as an associated array. The key in the associated array is the variable name, and the value is the value of the variable, for example, the variable "input" and value "4" in the first two sentences ",

The Code is as follows:

Class VariableExpression extends Expression {private $ name; // variable name private $ val; // variable value function _ construct ($ name, $ val = null) {$ this-> name = $ name; $ this-> val = $ val;} function interpret (InterpreterContext $ context) {if (! Is_null ($ this-> val) {$ context-> replace ($ this, $ this-> val); $ this-> val = null ;}} function setValue ($ value) {// used to set the variable value $ this-> val = $ value;} function getKey () {// this rewrites the getKey () of the parent class () method. When the lookup () method of the small container InterpreterContext calls the getKey () method of the instance of this class, it returns a string (that is, the variable name) instead of numeric index return $ this-> name ;}}

5. OperatorExpression operator Expression abstraction base class. This class inherits and combines the Expression abstraction base class. The implemented interpret () method mainly stores the calculation result of the Expression.

The Code is as follows:

Abstract class OperatorExpression extends Expression {protected $ l_op; // value on the left of the Expression protected $ r_op; // value on the right of the Expression function _ construct (Expression $ l_op, Expression $ r_op) {// during initialization, you can combine subclass instances that inherit the Expression class $ this-> l_op = $ l_op; $ this-> r_op = $ r_op;} function interpret (InterpreterContext $ context) {// mainly used to save the result of the expression test (saved to an instance of the InterpreterContext class) $ this-> l_op-> interpret ($ context ); // Save the value or calculation result of the Expression subclass instance to the instance of the InterpreterContext class $ this-> r_op-> interpret ($ context ); $ result_l = $ context-> lookup ($ this-> l_op ); // obtain the value or calculation result of the previous step $ result_r = $ context-> lookup ($ this-> r_op); $ this-> doInterpret ($ context, $ result_l, $ result_r); // The comparison operation is implemented by the inherited subclass.} protected abstract function doInterpret (InterpreterContext $ context, $ result_l, $ result_r );}

6. Expression sexpression, BooleanOrExpression, and BooleanAndExpression are equal expressions that inherit the OperatorExpression abstract base class, or expressions. There is only one method with the expression, doInterpret () internally calls the replace () of the InterpreterContext class () method To save the expression calculation result to an instance of the InterpreterContext class

The Code is as follows:

// Equal expression class extends sexpression extends OperatorExpression {protected function doInterpret (InterpreterContext $ context, $ result_l, $ result_r) {$ context-> replace ($ this, $ result_l = $ result_r) ;}// or expression class BooleanOrExpression extends OperatorExpression {protected function doInterpret (InterpreterContext $ context, $ result_l, $ result_r) {$ context-> replace ($ this, $ result_l | $ result_r) ;}// class booleandexpression extends OperatorExpression {protected function doInterpret (InterpreterContext $ context, $ result_l, $ result_r) {$ context-> replace ($ this, $ result_l & $ result_r );}}

So far, the classes related to this mode have been introduced. The above code has been tested. You can copy and paste it directly to view the results. Now let's take a look at the client code:

Client code 1:

$ Context = new InterpreterContext (); $ statement = new BooleanOrExpression (// you can try to replace this operator expression with BooleanAndExpression and run it to see the execution result. // you can try to change the instantiated parameter in LiteralExpression to another value to see the operation result, you can also change an explicit sexpression object to BooleanOrExpression or booleandexpression new Explicit sexpression (new LiteralExpression ('four '), new LiteralExpression ('four'), new explicit sexpression (new LiteralExpression ('B '), new LiteralExpression ('4'); $ statement-> interpret ($ context); if ($ context-> lookup ($ statement) {echo 'condition is true ';} else {echo 'condition not true ';}

Client Code 2:

$ Context = new InterpreterContext (); $ statement = new BooleanOrExpression (new BooleanAndExpression (new short sexpression (new LiteralExpression ('4'), new LiteralExpression ('4 ')), new Short sexpression (new LiteralExpression ('4'), new LiteralExpression ('4'), new short sexpression (new LiteralExpression ('B '), new LiteralExpression ('4'); $ statement-> interpret ($ context); if ($ context-> lookup ($ statement) {echo 'condition is true ';} else {echo 'condition not true ';}

Client code 3:

The difference between the original client code instance and the preceding client code is that the variable expression VariableExpression is used.

$ Context = new InterpreterContext (); $ input = new VariableExpression ('input '); // a variable input is defined here, but $ statement = new BooleanOrExpression (new syntax sexpression ($ input, new LiteralExpression ('four ') is not assigned ')), // here, the value of the variable expression and the text expression will be compared to whether the value is equal. new Short sexpression ($ input, new LiteralExpression ('4 '))); foreach (array ("four", "4", "52") as $ val) {$ input-> setValue ($ val ); // assign the value of print to the input variable. The value of input is $ val: <br/> "; $ statement-> interpret ($ context ); // compare and save the comparison result to the InterpreterContext object instance if ($ context-> lookup ($ statement )) {// obtain the comparison result print "condition is true <br/>";} else {print "condition is not true <br/> ";}}

The above code can run normally after testing. If you need it, you can copy it and run it to check the results.

The above is a common example of PHP object-oriented interpreter mode, which is all the content shared by the editor. I hope you can give us a reference and support for the house of friends.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.