1

I've recently started using this PHP-JS library.
It's basically a php wrapper over Google's V8 javascript engine.

The main reason of using it is that it can run isolated javascript code.
And return the outcome.

It's no problem for int and string values. Those are returned as-is.

But I found myself creating an array and i need to return it. I get:

PHP Fatal error: Cannot use object of type JS\Object as array

I'm doing this simple script:

<?php
$context = new JS\Context();
$script = "var arr = ". json_encode([2,3]).";x = arr.length";
var_dump($context->evaluate($script)); 
// int(2) - which is correct

But if I want to get the arr returned:

<?php
$script = "var arr = ". json_encode([2,3])."; arr;";
var_dump($context->evaluate($script));
// class JS\Object#1 (0) {}

Note: evaluate($stuff) returns the last variable in the script.

Is there any nice way of returning that value?


Update: After some digging, I've found a way to access data. What it does is encapsulate the array into a stdClass object:

$result = $context->evaluate($script);
echo $result->{0}; // outputs 2 
// also works for ->{1}

But it's still way too ugly to use in real-life

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45

1 Answers1

0

Figured out a way to extract array results of the evaluation:

$script = "var arr = ". json_encode([2,3]).";x = JSON.stringify(arr);";

At this point, x is a string:

var_dump($context->evaluate($script)); // string(5) "[2,3]"

Now all I needed to do is 'reverse' the JSON.stringify():

var_dump(json_decode($context->evaluate($script),true));
// array(2) {
//   [0] => int(2)
//   [1] => int(3)
// }

Update


Arrays returned as JS\Object are iterable. So this is valid:

$script = "var arr = ". json_encode([2,3]).";arr";
foreach($obj as $key=>$val){
    print_r($key);echo " => ";print_r($val);echo "\n";
}
// output
// 0 => 2
// 1 => 3

It's not that nice when the return array is nested:

$script = "var arr = ". json_encode([2,3,[1,4]]).";arr";
$obj = $c->evaluate($script);
foreach($obj as $key=>$val){
    print_r($key);echo " => ";print_r($val);echo "\n";
}
// output
// 0 => 2
// 1 => 3
// 2 => JS\Object Object() <- this needs looping too

For the second example a recursive method is required to parse all levels.

So I'm sticking with the JSON.stringify and json_decode($r, true);

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45