Variables Within Functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lordpoee
Forum Newbie
Posts: 3
Joined: Sat Sep 12, 2009 11:44 pm

Variables Within Functions

Post by lordpoee »

Hey guys, working on a might big project and here is what is going on.

Firstly: I have been trying to build a displayquery() function, it should work like this.

Code: Select all

 
function displayquery($qid, $table, $row, $where)
{
$sql[$qid]= "SELECT * FROM " .$table. " WHERE " .$row. " = '$where'";
$result[$qid] = mysql_query($sql[$qid]) or die(mysql_error());
 
It seems to call on the MySQL database just fine, but once the variables are loaded within the function it refuses to putput it once it is outside the function.

for example

Code: Select all

 
$num[0]= mysql_numrows($result[0]);
$a[0] = 0;
while ($a[0] < $num[0]) {
$playerid=mysql_result($result[0],$a[0],"playerid");
$[0]++;
}
 
it reports mysql_numrows() expects resource null given or some such, I am assuming that I need to somehow use that $this->result or something, am I close?
lordpoee
Forum Newbie
Posts: 3
Joined: Sat Sep 12, 2009 11:44 pm

Re: Variables Within Functions

Post by lordpoee »

Seems there is no easy way to build a display query, you just have to do it the long way :(

for example I have two display queries in the class I built

Code: Select all

 
// Here 1 is the query ID $qid
$dosql->display(1, "players", "player", $myplayername");
 
//Her 2 is the query ID $qid
$dosql->display(2, "players", "player", $target");
 
then try

Code: Select all

 
$dosql->health;
$dosql-tarHealth;
 
I think what I need to do is define the variable locally.

Code: Select all

 
// Here 1 is the query ID $qid
$dosql->display(1, "players", "player", $myplayername");
$health = $dosql->health;
 
$dosql->display(2, "players", "player", $target");
$health = $dosql->health;
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variables Within Functions

Post by requinix »

Variable scope. Variables outside a function are not accessible inside the function, and vice versa.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Variables Within Functions

Post by jackpf »

Unless you declare them global, or use the $GLOBALS array.
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Variables Within Functions

Post by peterjwest »

You need to return the value .e.g:

Code: Select all

 
function area($height, $width) { 
   return $height * $width; }
$area = area(2,3);
 
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Variables Within Functions

Post by jackpf »

Or pass by reference :D

Code: Select all

function area($width, $height, &$area)
{
$area = $width * $height;
}
 
area(10, 10, $area);
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Variables Within Functions

Post by peterjwest »

I would always recommend passing by return value wherever possible. I have three reasons:
1) It's clearer: if you only use a return value there is an obvious and separate input-output stream, e.g. $output = function($input). Also if you pass by reference it may not be obvious how the function is changing your variable, it might be overwriting, appending, adding, subtracting etc. when you return a value it allows you to choose what to do with it.
2) You don't have to predefine the variable e.g.

Code: Select all

$area = area(1,2)
//instead of:
$area = 0;
area(1,2,$area);
3) It allows temporary variables to be eliminated allowing your code to be more concise e.g.

Code: Select all

$volume = volume(area(1,2),3); 
//instead of:
area(1,2,$area)
volume($area,3,$volume);
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Variables Within Functions

Post by jackpf »

I completely agree, I hardly ever pass by reference to functions. Just thought I'd make sure the OP knew all the possible options :D

However, you don't have to initialise a variable before passing it by reference you know...
For example:

Code: Select all

<?php
error_reporting(E_ALL);
 
function foo(&$var)
{
    $var = 'blah';
}
 
echo $var; //will return a "undefined variable" error...
 
foo($var); //will not return an error
 
echo $var; //echos "blah"
?>
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Variables Within Functions

Post by peterjwest »

Ok, thanks. I have two reasons in that case :P.
lordpoee
Forum Newbie
Posts: 3
Joined: Sat Sep 12, 2009 11:44 pm

Re: Variables Within Functions

Post by lordpoee »

jackpf wrote:Unless you declare them global, or use the $GLOBALS array.
What I ended up doing is building a class.
example:

Code: Select all

 
class DoQuery{
var $playerid;
 
function displayquery($qid, $table, $row, $where)
{
$sql[$qid]= "SELECT * FROM " .$table. " WHERE " .$row. " = '$where'";
$result[$qid] = mysql_query($sql[$qid]) or die(mysql_error());
switch($qid)
{
case 0:
$num[0]= mysql_numrows($result[0]);
$a[0] = 0;
while ($a[0] < $num[0]) {
$this->playerid=mysql_result($result[0],$a[0],"playerid");
$a[0]++;
 
 
}
break;
 
}
 
$query = new DoQuery;
 
And then access those variables outside the class/function like so.

Code: Select all

 
$query->displayquery(0, "players", "player", $myplayername);
$playerid = $query->playerid;
 
This way I can make multiple SQl queries without mucking up my page with query after query.

Thanks for all the advice though and not being elitist or anything like so many IRC chat rooms (RTFM noob.) I have been programming in PHP for a few years and I am just now REALLy opening my eyes to what PHP can really do.

However, one of your replies peaked my interest, I am always in the business for "neater" code, smaller = faster.
peterjwest wrote:I would always recommend passing by return value wherever possible. I have three reasons:
1) It's clearer: if you only use a return value there is an obvious and separate input-output stream, e.g. $output = function($input). Also if you pass by reference it may not be obvious how the function is changing your variable, it might be overwriting, appending, adding, subtracting etc. when you return a value it allows you to choose what to do with it.
2) You don't have to predefine the variable e.g.

Code: Select all

$area = area(1,2)
//instead of:
$area = 0;
area(1,2,$area);
3) It allows temporary variables to be eliminated allowing your code to be more concise e.g.

Code: Select all

$volume = volume(area(1,2),3); 
//instead of:
area(1,2,$area)
volume($area,3,$volume);
Not exactly sure how to apply that to my project yet but you can be sure I'm gonna figure out how lol.
Last edited by lordpoee on Sun Sep 13, 2009 5:46 pm, edited 1 time in total.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Variables Within Functions

Post by jackpf »

Hmm...what are you actually trying to do??

Couldn't you just use MAX() in your query to select the highest playerid (if that's even what you're trying to do).
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Variables Within Functions

Post by peterjwest »

There are a number of misconceptions in your DoQuery class code. I'll try to outline them below:
1) A class should represent a concept, not an action. Functions and methods represent actions e.g. doQuery. Also 'do' is a vague word, you should try to be more specific. An improvement would be class 'Query' and function 'print', leading to: $query = new Query; $query->print();
2) You are using a class in a roundabout way to return a value, it would be better just to use a function.
3) $sql[$qid] is an array however you are using it like a variable. Only one value is ever stored in $sql because its deleted at the end of the function call. Its the same for $result[$qid], $a[0] and $num[0]
4) A switch statement is designed to select between multiple sections of code based on an input. You should be using an if statement to conditionally select the code (presuming that is your intention).
5) You don't need to break from a switch statement, you only need break to prematurely exit from loops (for, while, foreach, etc.)

Here's my version of your code, it does exactly the same thing:

Code: Select all

function displayQuery($qid, $table, $row, $where) {
    $result = mysql_query("SELECT * FROM " .$table. " WHERE " .$row. " = '$where'");
    if ($qid == 0) {
        for ($a = 0; $a < mysql_numrows($result); $a++) {
            $playerId = mysql_result($result,$a,"playerid");
        }
    return $playerId;
    }
}
 
//Example usage
$playerid = displayquery(0, "players", "player", $myplayername);
 
It will get the result. Then if $qid equals 0 it will iterate through each result and store playerId. Only the last playerId is stored (it is overwritten each time). Somehow I don't think this is what you wish to achieve.
Post Reply