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

Call a JavaScript Function Returning a String

See more JavaScript Examples

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

Chilkat PHP Downloads

Chilkat2 PHP
<?php

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

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

// function greet(name) {
//     return "Hello, " + name + "!";
// }

$sbScript = new StringBuilder();
$sbScript->Append('function greet(name) { return "Hello, " + name + "!"; }');

$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 greet("Michael")

    $funcCall = new JsonObject();

    // Create JSON specifying the function name and arguments

    // {
    //   "name": "greet",
    //   "args": [ "Michael" ]
    // }

    $funcCall->UpdateString('name', 'greet');
    $funcCall->UpdateString('args[0]', 'Michael');

    $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": "string",
//   "value": "Hello, Michael!"
// }

$retval = $result->StringOf('value');
echo $retval, "\n";

// Output:
// Hello, Michael!