Skip to content
Advertisement

Assign object attributes from the result of prepared statement

I’m wanting to create a new instance of my Class and assign it’s attributes the values that are returned. The reason for this is I’m creating a series of methods inheriting from the calling class, as opposed to using static methods which I already had working.

Example of what I’m using currently:

JavaScript

What I tried was writing an instantiation method that creates a new instance of my class, and then assign each attribute of the object the value it returns from an array from a tutorial I did. However, the tutorial was fairly outdated and didn’t use any new syntax or binding, so I was trying to rework this.

Example from the tutorial below:

JavaScript

What I was trying to do from the tutorial, was to return my result as an array using a while, and then assigning a variable by passing the built array into the static::instantation() method, but it doesn’t seem to ever be working correctly, as any public functions I create in my calling class (Admin for example) aren’t called after as they don’t exist due to the Class not being instantiated.

Advertisement

Answer

mysqli_result::fetch_object() accepts the class name as the first argument. You can pass the class name as an argument to that method and get the instance of the model. I am not sure why you have that much code but consider my example which I wrote based on your own code:

JavaScript

The output from that example is:

JavaScript

As you can see, the code created an instance of the class using late-static binding and it also assigned the value to a private property, which you can’t do otherwise.

P.S. My example is a little bit tidier. I added parameter typing and removed a lot of unnecessary code. In particular, I remove empty try-catch which is a terrible practice.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement