Accessing variables in the runtime

The PHP runtime allows an extension to create, read, update and delete local, global and super global variables. This tutorial extends the big decimal extension to add an extension function that accesses global variables. The function checks whether a global variable exists, and if it does, whether it contains a string that can be converted into a BigDecimal.

Use the following steps to extend the BigDecimal extension to add an extension function that accesses global variables.

  1. Add the following Java™ code to the BigDecimalExtension class:
    @XAPIFunction("is_global_bigdecimal")
    public void isGlobal(RuntimeContext ctxt) {
            RuntimeServices runtimeServices = getRuntimeServices();
            String variableName = ctxt.getStringArgument(0).getString(); 
            VariableService variables = runtimeServices.getVariableService();
            boolean isGlobal = variables.isVariable(VariableScope.Global, variableName);
            if (isGlobal == true) {
                    XAPIString value = variables.getString(VariableScope.Global, variableName);
                    try {
                            new BigDecimal(value.getString());
                            ctxt.setReturnValue(true);             
                    } catch (NumberFormatException nfe) {
                            ctxt.setReturnValue(false);            
                    }
            }       
    } 
    
  2. Change the sample.php code to exercise the new function.
    <?php    
    $answer = is_global_bigdecimal('value') ? 'Yes!' : 'No!';
    echo 'Is global big decimal? '.$answer.'<br>';
    $value = '111111111111111';
    $answer = is_global_bigdecimal('value') ? 'Yes!' : 'No!';
    echo 'Is global big decimal? '.$answer.'<br>';
    $value = 'Not a big decimal!';
    $answer = is_global_bigdecimal('value') ? 'Yes!' : 'No!';
    echo 'Is global big decimal? '.$answer.'<br>';
    ?>
    
  3. Run the IBM® WebSphere® sMash application and point a Web browser at http://localhost:8080/sample.php

The example uses the VariableService interface to query the runtime about global variables.

Version 1.1.30763