5

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:

  1. Since that code gets executed when getting things from the database, what do I do in case there is more than one row?

  2. When I passed the $trailhead back to the calling code, the variables were empty

  3. 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 :)

3
  • 2
    While new Object() makes sense, the proper way is $trailhead = new StdClass;. Commented Jun 3, 2011 at 18:37
  • If all you want is to package the database results into an object structure, then prefer settype($array,"object") or do a mysql_fetch_object right away. If you want to get more fancy then just cast or extend from an ArrayObject. -- In your case you still need an array list for multiple trailerhead results. Commented Jun 3, 2011 at 18:38
  • @kenforce What is the StdClass? I was thinking to initially declare things like $trailheads[] = new Trailhead; Would that be more reasonable? And do I need a $ at the beginning of the class name? You don't have it in your example. Commented Jun 3, 2011 at 18:44

3 Answers 3

4
  1. $trailheads[] = $trailhead;
  2. I'd do a print_r() of $trailhead to check that it's what you expect it to be. The default object type in PHP is going to be stdClass.
  3. Yes, that's going to be better, as it'll allow your Trailhead objects 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.
Sign up to request clarification or add additional context in comments.

1 Comment

That was very helpful - thank you! Got it all mostly working.
4

I think you should get in "contact" with some of the basics first. Objects in PHP have sort of a history. They are a relative to the array and there are two sorts of objects:

  • data-objects
  • class objects

data objects are called stdClass and that's actually what you were initially looking for:

$trailhead = new Object();

in PHP is written as:

$trailhead = new stdClass;

(with or without brackets at the end, both works)

You then can dynamically add members to it, like you did in the second part without declaring the variable (that works, too in PHP):

$trailhead->trailhead_name = $row['trailhead_name'];
$trailhead->park_id = $row['park_id'];

If you want to more quickly turn $row into an object, just cast it:

$trailhead = (object) $row;

That works the other way, too:

$array = (array) $trailhead;

As you can see, those basic data based objects in PHP do not hide their relationship to the array data type. In fact you can even iterator over them:

foreach($trailhead as $key=>$value) {
    echo $key, ' is ', $value, "<br>\n";
}

You can find lots of information about this in the PHP manual, it's a bit spread around, but worth to know the little basics before repeating a lot of names only to pass along the data that belongs together.

Next to these more or less stupid data objects, you can code complete classes that - next to what every stdClass can do - can have code, visibility, inheritance and all the things you can build nice stuff from - but this can be pretty complex as the topic is larger.

So it always depends on what you need. However, both type of objects are "real objects" and both should work.

class myClass {
    function importArray(array $array) {
        foreach($array as $key=>$value) {
            if(!is_numeric($key)) $this->$key=$value;
        }
    }
    function listMembers() {
        foreach($this as $key=>$value) {
            echo $key, ' is ', $value, "<br>\n";
        }
    }
}

$trailhead = new myClass();
$trailhead->importArray($row);

echo $trailhead->park_id;

Keep in mind that instead of creating a set of objects that merely does the same in each object (store data), you should just take one flexible class that is handling the job flexible (e.g. stdClass) because that will keep your code more clean.

Instead of coding a getter/setter orgy you can then spend the time thinking about how you can make the database layer more modular etc. .

Comments

1

Just pass back an array:

$trailhead = array(
    'trailhead_name' => $row['trailhead_name'],
    'park_id' => $row['park_id'],
    'trailhead_id' => $row['trailhead_id'],
)

Then either access it like:

$trailhead['park_id'];

or use the nifty list() to read it into variables:

list($trailhead_name, $park_id, $trailhead_id) = $trailhead;

3 Comments

I like list, but in that specific example, extract($trailhead); and job done ;).
Cool, I had wondered if there was something like extract() before.
Now I wonder why it does not work with objects ;) Probably worth to suggest the PHP team to close the circle - wait: extract(get_object_vars($object)); - but this will do an error as it's expected as a var by reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.