I was previously mostly scripting in PHP and now considering getting “more serious” about it 🙂
I am working on a hiking website, and I needed to put some values into an object that I then try to pass back to the calling code.
I tried doing this:
$trailhead = new Object ();
But the system sort of barfed at me.
Then I didn’t declare the object at all, and started using it like this:
$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];
That seemed to work reasonably ok. But there are at least 3 problems with this:
-
Since that code gets executed when getting things from the database, what do I do in case there is more than one row?
-
When I passed the $trailhead back to the calling code, the variables were empty
-
I actually am maybe better off making a real object for Trailhead like this:
class Trailhead { private $trailhead_name; private $park_id; private $trailhead_id; public function __construct() { $this->trailhead_name = NULL; $this->park_id = NULL; $this->trailhead_id = NULL; } }
What do people generally do in these situations and where am I going wrong in my approach? I know its more than one place 🙂
$trailheads[] = $trailhead;print_r()of$trailheadto check that it’s what you expect it to be. The default object type in PHP is going to bestdClass.Trailheadobjects to have functions. The way you’re currently doing it is basically taking advantage of none of PHP’s object functionality – it’s essentially an array with slightly different syntax.