The situation:
index.php:
<?php
include("foo.php");
include("baz.php");
foo("bar.php");
?>
baz.php:
<?php
$x = 42;
?>
foo.php:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
?>
bar.php:
<?php
echo $x;
?>
Zend notice: Undefined variable: x
Placing global $x; in bar.php removes the notice, but I understand why there is a notice about this in the first place.. Doesn't include pretty much work like including C headers? It would mean that the interpreted code would look like this:
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
$x = 42;
// this however, is included by a function...
// does the function's scope influence the stuff it includes?
echo $x; // undefined variable
?>
My editor is the Eclipse/Zend package.
I'm no expert, so please don't flame me if I'm wrong, but I think the file called by include_once or require_once is called in the context of the caller. Since function foo() won't know about $x then neither will any of its called includes. You could experiment by 'declaring' $x inside function foo() with the same setup as above.
I get a bunch of those notices since I'm almost allways goes with "$o .= 'foo'" without any definition. I'm just hiding them with error_reporting(E_ALL ^ E_NOTICE), but I don't know if it's the optimal way in this case.
It doesn't work even if the variable and the function are in the same file.
1 <?php
2
3 $x = 3;
4
5 function t()
6 {
7 echo $x;
8 }
9
10 t();
Prints nothing.
But add a global
1 <?php
2
3 $x = 3;
4
5 function t()
6 {
7 global $x;
8 echo $x;
9 }
10
11 t();
and you can see "3".
In a function you can't see global variables unless you declare it.
yes its the function scope that is causing your issues
if you replace
foo("bar.php");
with
include("bar.php");
you'll see that everything works fine because it puts it into the current scope and not functions scope
Related
I am trying to make a function that counts how many times it has been called
Here is my code:
<?php
function print_calls() {
count(print_calls);
}
print_calls();
?>
I want it to display how many times the function is called like
print_calls(); // 1
print_calls(); // 2
print_calls(); // 3
Something like this?
<?php
function callCount(){
static $calls=0;
echo $calls++;
}
callCount();
?>
You can use a static variable for this:
function print_calls() {
static $callCount=0;
printf("%d\n", ++$callCount);
}
Note that this only keeps the counts for the current process, so if you use this in a web server the count will be reset for each page you access. If you need persistent counts, you would have to write it to a file or use a $_SESSION variable.
Global variables may be dangerous. Be carefoul.
You can define a variable as counter and a function that uses that external variable.
php > $counter = 0;
php > function ciao() { global $counter; $counter++; echo $counter; }
From now, ... each time you call that function it print the variable incremented. This happens because the scope of $counter is not local to the function but global to the file.
php > ciao();
1
php > ciao();
2
php > ciao();
3
php > ciao();
4
php > ciao();
5
I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
This is what im trying to do:
I have a index.php and what im trying to do is read a value from this one, in another php using require_once, and returned the value modified, but it doesnt work for some reason, thanks everyone.
functions.php
<?php
function get_val(){
return $my_val*2;
}
?>
index.php
<?php
$my_val = 3;
require_once "functions.php";
echo get_val();
?>
So if u can help me, what i need to show is 6; but it doesnt show anything, i dont wanna use arguments, only global variables but it doesnt work,thanks.
$my_val variable is scope in function, you must use global variable in this case, example here:
functions.php
<?php
function get_val(){
global $my_val;
return $my_val*2;
}
?>
index.php
<?php
$my_val = 3;
require_once "functions.php";
echo get_val();
?>
you can see example here (From w3s)
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y, result: 15
This is PHP 5.4 code...
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function(){return abc($YesNo);});
echo $x['active']();
?>
Notice: Undefined variable: YesNo on line 7
Output Should be : Yes
if i directly put array in code by replace $YesNo like
<?php
function abc($YesNo){return $YesNo["value"];}
$x = array("active"=>function(){return abc(array("value"=>"Yes","text"=>"Yes"));});
echo $x['active']();
?>
output : Yes
which is correct output. Now what's the problem in first code. I need that for re-usability
Try this,
You can use use for passing data to a closure.
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
echo $x['active']();
?>
You provide your anonymous function with a parameter:
$x = array("active"=>function($param){return abc($param);});
then you call it:
echo $x['active']($YesNo);
You may use the use keyword to make your function aware of an external variable:
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
but it would be quite against the idea of reusability, in this case.
The problem is that your variable is not accessible within the function due to Variable Scope.
Because the array is defined outside of the function, it is not by default available inside the function.
There's a couple of solutions
Disclaimer: These are intended to fit within the scope of the question. I understand that they are not necessarily best practice, which would require a larger discussion
First Option:
You can declare the array within the function, like below. This is useful if you don't need access to it outside of the function.
function abc($YesNo){
$YesNo = array("value"=>"No","text"=>"No");
return $YesNo["value"];
}
Second Option:
Within your abc function, you can add the line global $YesNo. This is useful if you do need access to the array outside of the function:
function abc($YesNo){
global $YesNo;
return $YesNo["value"];
}
Other options exist (such as moonwave99's answer).
Finally:
Why are you putting an anonymous function within the array of $x? Seems like a path that will lead to problems down the road....
Your variable $YesNo needs to be visible in the scope of your anonymous function. You need to add global $YesNo as the first statement in that function:
So
$x = array("active"=>function(){return abc($YesNo);});
becomes
$x = array("active"=>function(){global $YesNo; return abc($YesNo);});
... also "value"=>"No" should be "value"=>"Yes" if you want it to return "Yes"
If we miss something it's the nature that compiler producing a warning .Anyway I wanted to neglect the warning or rid from showing the warnings in php programs.
Example Warning is :
Error(s), warning(s): PHP Notice: Undefined variable: z in
source_file.php on line 11
Below is an example which shows an warning : How we can neglect or suppress the warning?
<?php
$x=4;
$y=3;
function func($x=3 ,$y=4)
{
$z=$x+$y/$y+$x;
echo '$z';
}
echo $x;
echo $y;
echo $z;
func($x,$y);
?>
You are printing $z variable at line 11, which is not defined.
You've defined $x and $y, but no $z.
The $z in your "func" function exists in a scope of the function only and not the "main" script.
So, I guess is what you trying to do:
<?php
function func($x=3 ,$y=4)
{
$z=$x+$y/$y+$x;
return $z;
}
$x=4;
$y=3;
//Now $z is defined!
$z = func($x,$y);
echo $z;
?>
becouse you have not defined $z. correct code is given below.
<?php
$x=4;
$y=3;
$z="";
function func($x=3 ,$y=4){
$z=$x+$y/$y+$x;
echo $z;
}
echo $x;
echo $y;
echo $z;
func($x,$y);
?>
Variable $z has a function level scope as you declare it in a function Therefore, you are getting that warning.
Also, there is no need of defining your function as
function func($x=3 ,$y=4) {} // here you are limiting the function to perform calculation for only 3 and 4
As you are passing values to a function therefore define your function as
function func($x ,$y){}
and use that function in your code as many times as you want.
To achieve your desired result try the following code
$x=4;
$y=3;
function func($x=3 ,$y=4)
{
return $x+$y/$y+$x;
}
echo $x;
echo $y;
$z = func($x,$y);
echo $z;
It is trying to tell you that z is not defined from where you are trying to use it. Actually, it is only defined within the function func. Review the scope of variables in PHP.
Edit:
Q: How to clear the warning?
A: You need to either define z or suppress the warning from the compiler. I would strongly recommend that you define it. An answer below already gives a possible alternative to your code where the problem is solved.