PHPackages                             psf1/js4php5 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. psf1/js4php5

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

psf1/js4php5
============

JavaScript Interpreter for PHP

0.0.3(9mo ago)056MITPHPPHP &gt;=8.0.0

Since Jun 27Pushed 9mo agoCompare

[ Source](https://github.com/PSF1/js4php5)[ Packagist](https://packagist.org/packages/psf1/js4php5)[ Docs](http://github.com/psf1/js4php5)[ RSS](/packages/psf1-js4php5/feed)WikiDiscussions master Synced today

READMEChangelog (3)DependenciesVersions (5)Used By (0)

js4php5
=======

[](#js4php5)

What is this?
-------------

[](#what-is-this)

js4php5 is an ECMAscript/JavaScript interpreter, as defined by Ecma-262 3rd edition. It is *functional*, if slow and incomplete.

This project is an indirect fork of the [j4p5 bundle for Symfony](https://github.com/walterra/j4p5bundle), which in itself is based off of [j4p5 1.1](http://j4p5.sourceforge.net/). This project was originally started to modify and update j4p5 for use in the [StarsNT project](https://github.com/hiltonjanfield/starsnt). As the code is potentially useful for others, it was decided not to strip any functionality, but rather to clean up and modernize the code.

See the **Information** and **Bugs** sections below for more details.

Basic Usage
-----------

[](#basic-usage)

Terms:

- The *source script* is the original JavaScript/EcmaScript to be run.
- A *compiled script* is one that has been translated into PHP, ready to be run.
- A *loaded script* is resident in memory. js4php5 turns source scripts into PHP classes. Once loaded, PHP classes remain available in memory until the end of the session.
- A *cached script* is one that has been stored on disk.

Basic usage of the project is simply to call `JS::run()`. Example:

```
JS::run('var js4php5 = "It works!"; print(js4php5);');
```

Most of the other classes are not intended for direct usage, outside of what is documented here.

---

```
JS::run($script, [$id = null, [$forceRecompile = false, [$cacheToFile = true]]);
```

Compile, cache, and execute the script. Use already-loaded or cached versions if they exist, unless `$forceRecompile` is true.

Parameters:

- `$script` - the JavaScript code to execute.
- `$id` - Script ID to use when referencing, and as part of the class name and cache filename. If `null`, an ID will be generated using `md5($script)`.
- `$forceRecompile` - If true, the given script will be compiled even if a cached version is found.
- `$cacheToFile` - If true, the compiled script will be cached to file. If `$forceRecompile` is also true, the newly compiled script will replace the previous one in the cache.

Returns the value returned by the script, converted to a standard PHP value.

```
JS::getCurrentScriptId()

```

Returns the ID of the last run script. Use this to get the ID of a script for which you did not provide your own ID.

```
JS::getCurrentScriptFQCN()

```

Returns the Fully Qualified Class Name of the last run script. Once a script has been run, the class remains in memory until the end of the session.

`$myscript = JS::getCurrentScriptFQCN();` will grab the script reference so you can run it again at any time using `$myscript::run();`. However, there is very little overhead simply using JS::run('', 'myScriptID'); after the first call.

For those thinking about using js4php5 to run small scripts/functions repeatedly, as is our main use case in StarsNT: Testing shows that every time the object is called, it gets faster. Significantly faster after the first (loading and/or compiling) call, obviously, but continued speed increases occur on stock PHP installs (no code caching system). Tests on the dev machine have results along the lines of `[250ms, 40ms, 25ms, 18ms, 9ms]` when a small script is called five times.

```
JS::callFunction($name, array $parameters = [])

```

Function which calls a Javascript function from a loaded script. **Use with caution; only works on functions defined in the most recently loaded script!**`$myscript::callFunction('myfunctionname', [17, 'parameters', 'here']);`.

```
JS::convertReturnValue($value)

```

If you are calling a script manually as noted above (`$myscript::run()`) and need the return value of the script, you can use this function to convert it to a usable PHP value (`$result = JS::convertReturnValue($myscript::run());`). This function is automatically called by JS::run() and Runtime::callFunction() before a value is returned.

Parameters:

- `$value` - JavaScript returned object to convert to a PHP value.

```
JS::defineObject($objectName, [$functions = null, [$variables = null]])

```

Define your own JavaScript object. $functions is an array consisting of 'javascriptFunctionName' =&gt; 'PHPFunctionName'. Named PHP functions must exist in the global namespace. $variables is an array consisting of 'javascriptVariableName' =&gt; value. Values must be standard values; no objects or arrays. If you require this functionality, use the Runtime:: API directly. Example:

```
  JS::defineObject('external', ['sha1' => 'js_sha1', 'add' => 'js_add'], ['PI' => 3.14159]);

```

This creates a JavaScript object called `external` with:

- external.sha1(...)
- external.add(...)
- external.PI

```
JS::setCacheDir($directory);

```

Set the directory where cached files are kept. Returns FALSE if the directory is invalid or cannot be written to. If not called, the cache dir defaults to the temporary directory reported by PHP (sys\_get\_temp\_dir()).

We can extend the inicial runtime context setting a callable before run:

```
Runtime::setStartExtender([self::class, 'jsStartExtender']);

```

And the method callable maybe like this:

```
... class definition y with section that execute javascript code ...

  /**
   * Extend runtime context after start it.
   */
  public static function jsStartExtender() {
    // Add Console object with log method.
    // We can use it with: `Console.log("Hi world!");`
    $console = new jsConsole();
    Runtime::define_variable("Console", $console);
    Runtime::push_context($console);
    Runtime::define_function([jsConsole::class, 'log'], "log");
    Runtime::pop_context();
  }

... Other things in the class ...

```

And the jsConsole class:

```
