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);
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:
CREATE TABLE people (
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.name.length);
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.