Page 1 of 1

unnecessary declarations ?

Posted: Thu Jul 27, 2006 11:07 am
by tdnxxx444
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Just a generic example.  Which way is better?

1.

Code: Select all

$query = "SELECT user_id, user_name FROM users";
$result = mysql_query($data);
$data = msql_fetch_assoc($result)

<html>
$data['user_id']
$data['user_name']
getBillingFromId($data['user_id'])
</html>
2.

Code: Select all

$query = "SELECT user_id, user_name FROM users";
$result = mysql_query($data);
$data = msql_fetch_assoc($result)

$user_id = $data['user_id']
$user_name = $data['user_name']
$billing = getBillingFromId($data['user_id'])

<html>
$user_id
$user_name
$billing
</html>

Is #2 unnecessary declarations that we don't need?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Jul 27, 2006 11:14 am
by feyd
That seems like a silly question.. they are optional, therefore not needed. I guess the real question is which one is more a "best practice" than the other and why?

Personally, I don't like either. For only the most basic of pages, number one is my preference. This sort of page is generally just a quick test page to see if a concept will work. For anything more, I always try to use templating, which could be either one if I used PHP as the template engine.

Posted: Thu Jul 27, 2006 11:20 am
by Benjamin
I think your confused about undefined variables. Your first example is just fine, but something like this isn't...

Code: Select all

$rand = rand(0,50);

if ($rand > 25)
{
    $thisValue = 'I am set';
}

echo $thisValue;
Now if the random number is smaller than 26, $thisValue won't be set, and when you try to echo it, PHP will generate a notice. A more correct example would be..

Code: Select all

$rand = rand(0,50);

if ($rand > 25)
{
    $thisValue = 'I am set';
}

if (isset($thisValue)) echo $thisValue;

Posted: Thu Jul 27, 2006 11:23 am
by tdnxxx444
Well the reason I am asking, is because though the 2nd example can be seen as having unnecessary variable declarations, it may help in the future to know where your variables are coming from.

Posted: Thu Jul 27, 2006 11:49 am
by jamiel
I only break away from my array if I plan to alter that variable but don't want it to affect my array. Otherwise it is unneccessary unless it improves readability for you and you are sure you are not going to use your array again.