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