Author Topic: Classes and Confusion  (Read 756 times)

Offline Sinzygy

  • Level 28
  • **
  • Posts: 420
  • Reputation: +11/-0
    • View Profile
Classes and Confusion
« on: October 14, 2007, 09:08:54 AM »
Ok, I'm working on something and I wrote the following code:
Code: [Select]
class castle
{
function castle($id)
{
global $db;
$sql = "SELECT * FROM castles WHERE castleid = '$id'";

$exclude_vars = array("userid");
$rs = $db->Execute($sql);
$rs = $rs->GetRows();

foreach($rs[0] as $key => $value)
{
if(!in_array($key,$exlucde_vars))
{
$this->$key = $value;
}
}
}
}

And it seems to be working. And this is where I'm confused:

It seems to be working to use new class-variables without declaring them first. I mean, usually I'd write out all the variables I want (var $food, var $gold, etc.) but apparently I don't need to do that. Or is it just my local version of PHP that let's me do it this way.

Offline Zeggy

  • Global Moderator
  • Level 35
  • *****
  • Posts: 1,187
  • Reputation: +13/-4
    • View Profile
Re: Classes and Confusion
« Reply #1 on: October 14, 2007, 10:49:18 AM »
To be honest, I'm not sure of when you need to 'declare' a variable first before you assign a variable to it.
I've noticed that it is required sometimes when I'm working with arrays in classes.
« Last Edit: October 14, 2007, 10:58:28 AM by Zeggy »

Offline beam

  • Level 15
  • *
  • Posts: 132
  • Reputation: +2/-0
  • Dance Commander
    • View Profile
Re: Classes and Confusion
« Reply #2 on: October 14, 2007, 10:50:48 AM »
When you use:

Code: [Select]
$this->$key = $value

You are declaring them, that is the declaration statement. For example, say $rs[] is this:

Code: [Select]
$rs = array("one" => 1, "two" => 2, "three" => 3);

Now, you're taking that array and declaring the keys of the arrays as class variables. After you exectute that last inner for loop, you'll be able to access the following $this->one, $this->two, and $this->three because you declared them as class variables inside the for loop.

I hope that helps, unless I misunderstood what you were asking.

Offline Sinzygy

  • Level 28
  • **
  • Posts: 420
  • Reputation: +11/-0
    • View Profile
Re: Classes and Confusion
« Reply #3 on: October 14, 2007, 01:09:38 PM »
thanks beam, that was exactly what I was asking.

It was only that I always used to write each variable at the beginning of a class with "var $somevar;". But this saves me a sh*tload of time :)

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal