asmblah / uniter

🎉 PHP in the browser and Node.js => Docs: https://phptojs.com/
https://asmblah.github.io/uniter/
Other
446 stars 42 forks source link

Non-numeric JS arrays not properly handled #35

Closed dave-irvine closed 7 years ago

dave-irvine commented 8 years ago
var php = require('uniter').createEngine('PHP');
php.getStdout().on('data', function (text) { console.log(text); });

var jsFunction = function () {
    var arr = [];
    arr['bobs'] = 'burgers';
    return arr;
};

php.expose(jsFunction, 'jsFunction');

php.execute('<?php print var_dump($jsFunction());');

array(0) {
}
IngwiePhoenix commented 8 years ago

I think you are having a misunderstanding.

var arr = [];
arr["ham"] = "burgers";

is NOT the same as in PHP. Arrays in JavaScript take numerical indices - and not strings. So in the snipped above, you could've also written:

var arr = [];
arr.ham = "burgers";

...and it'd been the same. Generally, everything in JavaScript is an Object - same applies for arrays. So when you assign a new member to an array, you are not guaranteed that it carries over in Uniter, since only numerical indices are passed. In fact:

Ingwie@Ingwies-MBP.Speedport_W723_V_Typ_A_1_01_012 ~/W/D/DIFM $ node
> var arr = [];
undefined
> arr.foo = "bar";
'bar'
> arr
[ foo: 'bar' ]
> arr.length
0
> for(var i=0; i<arr.length; i++) console.log(i, arr[i])
undefined

... and this conversion might be the case.

So:

With iterating, I mean:

> arr.forEach(console.log.bind(console))
undefined

Nothing happens.

dave-irvine commented 8 years ago

For sure, I know that JS arrays would usually need to be numerically indexed, but just like in #39 where I would like Uniter to convert from a PHP convention that JS doesnt understand, I'd like to be able to send back an array in the format that PHP understands even if JS doesnt.

Alternatively as long as I can pass back an Object with properties and it gets converted to an array on PHP's side, that would work too.

asmblah commented 8 years ago

Thanks for reporting this @dave-irvine, it should now be fixed in the latest PHPCore version (v3.17.3+), where your original code snippet now outputs

array(1) {
  ["bobs"]=>
  string(7) "burgers"
}

Cheers!

asmblah commented 7 years ago

Closing as I think the fix referenced above does what we need, but feel free to reopen if needed.

Thanks!