Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\Js;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;

// This is the JavaScript function we'll call:

// function isEven(number) {
//     return number % 2 === 0;
// }

$sbScript = new StringBuilder();
$sbScript->Append('function isEven(number) { return number % 2 === 0; }');

$js = new Js();

$result = new JsonObject();
$result->EmitCompact = false;

// Call Eval to add the function to the context's global object
try {
    $js->Eval($sbScript, $result);

    // ------------------------------------------------------------------------------
    // Call the function isEven(8)

    $funcCall = new JsonObject();

    // Create JSON specifying the function name and arguments

    // {
    //   "name": "isEven",
    //   "args": [ 8 ]
    // }

    $funcCall->UpdateString('name', 'isEven');
    $funcCall->UpdateInt('args[0]', 8);

    $js->CallFunction($funcCall, $result);
} catch (\Chilkat2\Exception $e) {
    // Examine the result for an exception.
    echo $result->Emit(), "\n";

    // Also examine the LastErrorText.
    echo $e->getMessage(), "\n";
    exit;
}

echo $result->Emit(), "\n";

// Output:
// {
//   "type": "bool",
//   "value": true
// }

$retval = $result->BoolOf('value');
echo ($retval ? 'true' : 'false'), "\n";

// Output:
// true