Using native arrays in php

I was having a hard time recreating this in haxe $opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]

I tried php.Syntax.assocDecl and php.Lib.associativeArrayOfObject but didn’t get the resulted output I was looking for… Can anyone give me a proper example of how to do this? and then let’s say you create the assoc array is there syntax for the access to the value by key?

P.S. I did get this working but the question still remains. Here’s code that did work for me.
var field1 = php.db.PDO.ATTR_ERRMODE;
var field2 = php.db.PDO.ERRMODE_EXCEPTION;
var opt = php.Syntax.code("[{0}=>{1}]", field1, field2);

Not actually helpful for the syntax use case itself but I happened to run into the exact same situation before :slight_smile: There’s a setAttribute method too:

This is not an associative array. This is an indexed array with non-continuous indices.
It’s my oversight I didn’t implement a way to declare such arrays. Will do it for Haxe 4.1:

Meanwhile you can do this to stay type-safe:

var opt = new php.NativeIndexedArray(); // or Syntax.arrayDecl();

which will generate following php code:

$opt = [];

Ahh thanks that makes sense now that you point it out.

Can you explain the proper getter and setter syntax for a associative array? I’m trying to figure out how to interact with the results of a FETCH_ASSOC PDO query by using the key to access the value.

Let’s say you have a table of the following structure:

  name VARCHAR(50);
  age INT;

Then you can fetch rows like this:

var row:php.NativeAssocArray<Any> = pdoStmt.fetch(PDO.FETCH_ASSOC);
var age:Int = row['age'];
var name:String = row['name'];

Or if you need to work with the fetch results a lot, you can create an abstract for boilerplate:

abstract PeopleRow(php.NativeAssocArray<Any>) {
  public var name(get,never):String;
  inline function get_name():String {
    return this['name'];

  public var age(get,never):Int;
  inline function get_age():Int {
    return this['age'];

and then work with fetch results in a type-safe manner:

var person:PeopleRow = pdoStmt.fetch(PDO.FETCH_ASSOC);
trace(person.age >= 13);

Thank you for that example, I noticed immediately a problem with my tests, I had been using nativeArray, and so when I did tests with NativeAssocArray I completely overlooked the fact that it has a Type definition on the end… duh! Of course that makes sense, I wonder why nativeArray doesn’t have any specified… but now I have everything working as expected! Your example of overriding get is interesting too and I’ll have to remember that. Thanks for your work on php target, I have been away from haxe for 10 years and came back because I saw the value of using this for a back end to a flutter app, and it’s been great.

Because that’s how it was defined in the previous Haxe->PHP implementation. And I was trying to keep new implementation backward compatible.