PHP function call not working - presumed casting problem? - php

Why does THIS not work when called via e.g. wd(1) (it always returns '-2')?
$zoom=$user['zoom'];
function wd($hrs){
return $hrs*$zoom-2;
}
But THIS works fine:
function wd($hrs){
return $hrs*30-2;
}
Assuming this was a casting problem, I tried all sorts of variations like
(int)$hrs * ((int)$zoom)
or
(int)$hrs * (float)$zoom
but no success :(
Any help would be appreciated.
(And BTW, does it matter whether the function is located within
include('header.php')
-- although I tried it both within and outside the header?)

EDIT: You should pass that variable as an argument to the function, but if you absolutely need to keep the variable global, do the following.
You need to bring the global into scope:
$zoom=$user['zoom'];
function wd($hrs){
global $zoom;
return $hrs*$zoom-2;
}

This isn't a casting issue - it's because you're trying to use a variable that's out of scope.
Whilst you'll need to read the PHP docs for the full low-down, at a basic level, you can only access variables that are defined within the same function or method. (Although you can use the global keyword to access global variables. That said, global variables are less than ideal.)
As such, you could simply update your function to also pass in 'zoom' as a parameter as follows:
function wd($hrs, $zoom){
return $hrs*$zoom-2;
}

$zoom=$user['zoom'];
function wd($hrs){
// there is no variable $zoom within the function's visibility scope
// so you will get a "Notice: undefined variable 'zoom'" here.
return $hrs*$zoom-2;
}
see http://docs.php.net/language.variables.scope

Related

PHP cannot get value of returned variable of function

I have a little function that has a string parameter. Now I want a variable defined within that function to be known outside of that function where the function is being executed.
function somefunc($hello) {
$hello = "hi";
$bye = "bye";
return $bye;
}
And using that function in another php script.
somefunc("hi");
echo $bye;
The other script in which the function is being used and in which I'm trying to echo out the variable keeps telling me that the variable bye has not been defined. How can I get its value without making it global? The other script has the function included in it properly, so this cant be the problem.
Thanks in advance for any help!!
Your syntax is the problem. To fix the current issue you need to first define a variable with the return variable or echo it.
function somefunc($hello) {
$hello = "hi";
$bye = "bye"
return $bye;
}
echo somefunc("hi"); // bye
// --- or ---
$bye = somefunc("hi");
echo $bye; // bye
The variable defined within that function cannot be accessed outside of its context (the function).
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
For a better understanding of variable scopes check out the docs in the PHP manual; they are pretty good at breaking it down.
You could also look at global references of variable in the PHP manual and it may work for what you are trying to do.

Defining a global variable, and including functions that require it?

I have six functions that require a global variable. In an attempt to reduce redundancy, I wrote a new function that is triggered rather than triggering all six. This one function has a global $var that is required by the other functions.
So, it looks like this
function one_function_for_the_rest() {
global $importantVar;
functionOne();
functionTwo();
functionThree();
}
but the global variable is not being seen by the called functions. Am I doing this incorrectly, or is this a limitation I was not aware of?
You're not doing it correctly as the variable is defined when on_function_for... is called. An easier way for this would be just to have $importantVar; at the start of the code.
Or wrap your functions inside a class and put the variable inside the class.
e: so basically do : function myFunc($important) { stuff } and when calling the function do myFunc($importantVar)
example :
$asd = "lol";
class myclass {
public function lol($asd) {
echo $asd;
}
}
$obj = new myclass;
$obj->lol($asd);
You're not doing it correctly. Each function either needs to use the global scope identifier, like global $importantVar;, or have $importantVar passed as a parameter. Otherwise, the other functions don't have $importantVar in their respective scopes.
Simply calling a function from within one_function_for_the_rest does not tell that other function anything about global variables or variables used in one_function_for_the_rest. In technical terms, your function calls do not bring $importantVar into the respective scopes of functionOne, functionTwo, or functionThree.
PHP does not have the same scoping rules as most other languages have. That is the downside to not having to declare variables with var as in JavaScript or other similar constructs.
Basically in PHP, every function used is only available in that function. There are three exceptions:
The global keyword
The $this variable inside objects. This one is also "magic" as it's also available inside anonymous functions defined inside a class.
When declaring an anonymous functions you can bind variables to it using use.

Why do I have access to a variable outside of a function but not within?

I have a bunch of HTML and PHP code and in the template file it works fine but I'm trying to put it in a PHP function and now when I run the page I get the error Undefined variable: variableName
Here's some code:
function testFunction()
{
foreach ($variableName as $variable):
echo 'tasf';
endforeach;
}
Inside that function $variableName cannot be found but if I move it outside the function it can be found just fine. I'm doing this within a symfony php template file if it matters.
Simple issue of variable scope. If that variable is defined outside the function then either you need to pass it there or declare it global
See Manual Here
PHP Variable Scope
$str = 'Hello World';
echo $str; // works fine
function foo($bar){
echo $bar; // passed as function argument. works fine
}
foo($str);
function bar(){
global $str;
echo $str; // passed from global. works fine
}
Function scope means that variables referenced inside a function, must be declared within it, or passed...
function testFunction($variableName)
{
foreach ($variableName as $variable):
echo 'tasf';
endforeach;
}
Here's a link to the PHP manual on Variable Scope.
Under no circumstances should you resort to using global variables. There is always a better way, and doing so is considered poor practice. It makes your code difficult to follow as it means anyone else may have to read all of it in order to understand what's going on.
You need to use the global keyword to make this happen.
global should be used sparingly however, and can have unintended side effects.

Superglobals can't be accessed via variable variables in a function?

I can't access superglobals via variable variables inside a function. Am I the source of the problem or is it one of PHP's subtleties? And how to bypass it?
print_r(${'_GET'});
works fine
$g_var = '_GET';
print_r(${$g_var});
Gives me a Notice: Undefined variable: _GET
PHP isn't able to recognize that this is a global variable access:
It compiles $_GET and ${'_GET'} to the same opcode sequence, namely a global FETCH_R. ${$g_var} on the other hand will result in a local FETCH_R.
This is also mentioned in the docs:
Superglobals cannot be used as variable variables inside functions or class methods.
You can possibly bypass it using $GLOBALS superglobal variable. Instead of writing
function & getSuperGlobal($name) {
return ${"_$name"};
}
you can write
function & getSuperGlobal($name) {
return $GLOBALS["_$name"];
}
and the results will equal.
It seems that the last PHP versions are dealing fine with that problem.
Next code works fine with PHP 5.5.9.
<?php
function foo() {
print_r(${'_SERVER'});
}
foo();

Function scopes in regards with includes in PHP

I'm having a bit of trouble understanding includes and function scopes in PHP, and a bit of Googling hasn't provided successful results. But here is the problem:
This does not work:
function include_a(){
// Just imagine some complicated code
if(isset($_SESSION['language'])){
include 'left_side2.php';
} else {
include 'left_side.php';
}
// More complicated code to determine which file to include
}
function b() {
include_a();
print_r($lang); // Will say that $lang is undefined
}
So essentially, there is an array called $lang in left_side.php and left_side2.php. I want to access it inside b(), but the code setup above will say that $lang is undefined. However, when I copy and paste the exact code in include_a() at the very beginning of b(), it will work fine. But as you can imagine, I do not wish to copy and paste the code in every function that I need it.
How can I alleviate this scope issue and what am I doing wrong?
If the array $lang gets defined inside the include_a() function, it is scoped to that function only, even if that function is called inside b(). To access $lang inside b() you need to call it globally.
This happens because you include 'left_side2.php'; inside the include_a() function. If there are several variables defined inside the includes and you want them to be at global scope, then you will need to define them as such.
Inside the left_side.php, define them as:
$GLOBALS['lang'] = whatever...;
Then in the function that calls them, try this:
function b() {
include_a();
print_r($GLOBALS['lang']); // Now $lang should be known.
}
It is considered 'bad practice' to use globals where you don't have to (not a consideration I subscribe to, but generally accepted). The better practice is to pass by reference by adding an ampersand in front of the passed variable so you can edit the value.
So inside left_side or left_side2 you would have:
b($lang);
and b would be:
function b(&$lang){...}
For further definitions on variable scopes check this out

Categories