PHP Requires Chilkat v11.4.0+
Chilkat2 PHP
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat PHP Downloads
<?php
use Chilkat2\Js;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;
// This is the JavaScript function we'll call:
// function getSettings() {
// return {
// theme: "dark",
// notifications: true,
// version: 1.0
// };
// }
$sbScript = new StringBuilder();
$sbScript->Append('function getSettings() {');
$sbScript->Append(' return {');
$sbScript->Append(' theme: "dark",');
$sbScript->Append(' notifications: true,');
$sbScript->Append(' version: 1.0');
$sbScript->Append(' };');
$sbScript->Append('}');
$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 getSettings()
$funcCall = new JsonObject();
// Create JSON specifying the function name and arguments
// The function has no arguments, so we only specify the name.
// {
// "name": "getSettings",
// }
$funcCall->UpdateString('name', 'getSettings');
$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": "object",
// "value": {
// "theme": "dark",
// "notifications": true,
// "version": 1
// }
// }
// Examine the object's members
echo 'theme: ', $result->StringOf('value.theme'), "\n";
echo 'notifications: ', ($result->BoolOf('value.notifications') ? 'true' : 'false'), "\n";
echo 'version: ', $result->IntOf('value.version'), "\n";
// Output:
// theme: dark
// notifications: True
// version: 1