PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS


these objects compares the VariableExpression object stored in $input with a LiteralExpression
containing the string "four"; the second compares $input with a LiteralExpression object containing
the string "4".


Now, with my statement prepared, I am ready to provide a value for the input variable, and run the
code:


foreach ( array( "four", "4", "52" ) as $val ) {
$input->setValue( $val );
print "$val:\n";
$statement->interpret( $context );
if ( $context->lookup( $statement ) ) {
print "top marks\n\n";
} else {
print "dunce hat on\n\n";
}
}


In fact, I run the code three times, with three different values. The first time through, I set the
temporary variable $val to "four", assigning it to the input VariableExpression object using its
setValue() method. I then call interpret() on the topmost Expression object (the BooleanOrExpression
object that contains references to all other expressions in the statement). Here are the internals of this
invocation step by step:



  • $statement calls interpret() on its $l_op property (the first EqualsExpression
    object).

  • The first EqualsExpression object calls interpret() on its $l_op property (a
    reference to the input VariableExpression object which is currently set to "four").

  • The input VariableExpression object writes its current value to the provided
    InterpreterContext object by calling InterpreterContext::replace().

  • The first EqualsExpression object calls interpret() on its $r_op property (a
    LiteralExpression object charged with the value "four").

  • The LiteralExpression object registers its key and its value with
    InterpreterContext.

  • The first EqualsExpression object retrieves the values for $l_op ("four") and $r_op
    ("four") from the InterpreterContext object.

  • The first EqualsExpression object compares these two values for equality and
    registers the result (true) together with its key with the InterpreterContext object.

  • Back at the top of the tree the $statement object (BooleanOrExpression) calls
    interpret() on its $r_op property. This resolves to a value (false, in this case) in
    the same way as the $l_op property did.

  • The $statement object retrieves values for each of its operands from the
    InterpreterContext object and compares them using ||. It is comparing true and
    false, so the result is true. This final result is stored in the InterpreterContext
    object.
    And all that is only for the first iteration through the loop. Here is the final output:


four:
top marks

Free download pdf