Bolli
Bolli

Reputation: 5274

Method returns right value outside of function, inside function returns NULL

Can someone help me understand this? It seams like I have done this a 100 times already, but for some reason I can't get it to work now.

I have a MySQL class where I do my SQL stuff.

I have a file called ajax.php which I do some AJAX requests to. In this file I have:

$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
$show =$mysql->count('temp_vipalm', "21");   
var_dump($show);

This returns the correct value as I expected. Now I want to use this in a function, so I can make it a little more dynamic, so in the same ajax.php file I create this function:

function menu($barid,$type)
{
    //echo $barid; // returns correct value
    //echo $bartype; //returns correct value

$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
   //usually $barid and $type goes in here, but I hardcoded the values for testing.
$show =$mysql->count('temp_vipalm', "21");   
var_dump($show);
}

Now when running menu('21', 'temp_vipalm'); it returns NULL.

No matter what I do, it keeps returning NULL when inside the function - can anyone help me understand what's going on?

Upvotes: 0

Views: 63

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

The variables $server, $dbuser, $dbpass, $dbselect are not declared in the scope of the function, you should declare them as global assuming they're defined in the global env.

Upvotes: 1

TonyWilk
TonyWilk

Reputation: 1477

There's two things to be aware of:

  1. global variables must be declared global inside a function
  2. the variable must already have been initialised

so this works fine:

<?php
$fred=42;

function printFred(){
  global $fred;   // declare it global
  echo "fred is: ". $fred . "\n";
}

printFred();
?>

whereas this does not do what you might expect:

<?php

echo "Starting program...\n";
printStuff();
echo "the end";
exit();


$jim="Hello I'm jim";

function printStuff(){
  global $jim;
  echo $jim . "\n";
}
?>

because, in this case, the statement "$jim="Hello I'm jim";" is never executed.

Yours, TonyWilk

Upvotes: 1

Travesty3
Travesty3

Reputation: 14469

Your $server, $dbuser, $dbpass, and $dbselect variables are global. Within the function scope, you'll have to declare that those variables are coming from the global scope. Try this:

function menu($barid, $type) {
{
    global $server, $dbuser, $dbpass, $dbselect;
    $mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
    // ...
}

Note: It would be a better idea to make these constants instead of variables. It's usually best to avoid variables in the global scope. If you accidentally overwrite one of those values somewhere else in your code, this function will use the wrong values.

Upvotes: 1

Related Questions