This is something that’s been bugging me with PHP for a while now and I still can’t figure out how I would do it. Basically at the moment for my SQL class I’m dumping the results in an array and converting them to an object to give something like this:
$first_post = $Post->find(1);
(I’ve also been trying to get the syntax to look like: $Post::find(1); but that’s a different and purely aesthetic issue altogether)
and then you can use first_post like so:
$first_post->title;
This is done by just converting the contents of $post->find(1) to an object like so:
$first_post = (object) array("title" => "blah");
and I know that instantiates a new STDClass but I can’t figure out how to bind methods to that new instance of STDClass. It’s mainly so I can do stuff like:
$posts = $Post->all();
$last_post = $posts->last();
$specific = $posts->find("name" => "hello");
Any ideas how I would get PHP to do something like this?
When using the scope resolution operator you are accessing static methods and/or constants. These are methods that work on the class rather than an instance of the class. For example:
As for creating an object for the post from an array, it’s probably better to either create your own
Postclass and populate it accordingly or use one of the database functions that return the table data as an object rather than array such asmysqli_result::fetch_objectormysql_fetch_object.If creating your own Post class, you can store the database information in an array and use the
__call(),__get()and__get()Magic Methods to access that data. For example: