The powerful bridge between PHP and Javascript
Execute JavaScript right from your PHP code and share variables between JavaScript and PHP.
Why PHP-JS
Powerful
PHP-JS is powerful. Almost all concepts from PHP can be assigned to a Javascript context and used from within Javascript code: scalar PHP variables, but also arrays, objects and functions. Special PHP features like magic member functions and SPL interfaces are automatically transformed into their Javascript counterparts.
Easy
The PHP-JS library takes care of converting your PHP variables into Javascript variables -- even when your variables are complex nested arrays or objects. All you have to do is assign the PHP variables, PHP-JS takes care of the rest. It works the other way around too: variables returned from Javascript are transformed back into PHP variables and can be processed by your PHP code.
Safe
The javascript runs in a seperated safe environment. The only PHP functions and variables that are accessible from Javascript are the ones that you assigned.
Example
<?php
// create a new scripting context
$context = new JS\Context;
// assign all sorts of PHP variables to it: strings, numbers, objects (even objects
// with magic methods like __toString and __invoke or that implement SPL interfaces
// like ArrayAccess and Iterator). Inline functions can be assigned too.
$context->assign("value1", "this is a string value");
$context->assign("value2", 1234);
$context->assign("value3", new MyClass());
$context->assign("value4", array(1, 2, 3, 4));
$context->assign("value5", function($a, $b) { return true; });
// the script that we're about to evaluate might throw an exception
try
{
// execute a user supplied javascript
$result = $context->evaluate(file_get_contents("script.js"));
// show the return value of the script (value of the last expression in the script)
var_dump($result);
}
catch (Exception $exception)
{
// a Javascript exception was thrown, we can handle that as a normal PHP exception
trigger_error("exception from script: ".$exception->getMessage());
}
?>