php中静态变量变量 变量是什么意思

Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的
PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了
include 和 require 引入的文件。例如:
这里变量 $a 将会在包含文件
b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。例如:
这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量
$a,而且在这个范围内,它并没有被赋值。你可能注意到
PHP 的全局变量和 C 语言有一点点不同,在 C
语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能不小心就改变了一个全局变量。PHP
中全局变量在函数中使用时必须声明为 global。
global 关键字
首先,一个使用 global 的例子:
Example #1 使用 global
&?php$a&=&1;$b&=&2;function&Sum(){&&&&global&$a,&$b;&&&&$b&=&$a&+&$b;}Sum();echo&$b;?&
以上脚本的输出将是“3”。在函数中声明了全局变量
之后,对任一变量的所有引用都会指向其全局版本。对于一个函数能够声明的全局变量的最大个数,PHP 没有限制。
在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义
数组。前面的例子可以写成:
Example #2 使用
替代 global
&?php$a&=&1;$b&=&2;function&Sum(){&&&&$GLOBALS['b']&=&$GLOBALS['a']&+&$GLOBALS['b'];}Sum();echo&$b;?&
是一个关联数组,每一个变量为一个元素,键名对应变量名,值对应变量的内容。
之所以在全局范围内存在,是因为 $GLOBALS 是一个。以下范例显示了超全局变量的用处:
Example #3 演示超全局变量和作用域的例子
&?phpfunction&test_global(){&&&&//&大多数的预定义变量并不&"super",它们需要用&'global'&关键字来使它们在函数的本地区域中有效。&&&&global&$HTTP_POST_VARS;&&&&echo&$HTTP_POST_VARS['name'];&&&&//&Superglobals&在任何范围内都有效,它们并不需要&'global'&声明。Superglobals&是在&PHP&4.1.0&引入的。&&&&echo&$_POST['name'];}?&
使用静态变量
变量范围的另一个重要特性是静态变量(static
variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:
Example #4 演示需要静态变量的例子
&?phpfunction&Test(){&&&&$a&=&0;&&&&echo&$a;&&&&$a++;}?&
本函数没什么用处,因为每次调用时都会将
$a 的值设为 0 并输出
0。将变量加一的 $a++
没有作用,因为一旦退出本函数则变量
$a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量
$a 定义为静态的:
Example #5 使用静态变量的例子
&?phpfunction&test(){&&&&static&$a&=&0;&&&&echo&$a;&&&&$a++;}?&
现在,变量 $a 仅在第一次调用 test() 函数时被初始化,之后每次调用 test() 函数都会输出
$a 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。以下这个简单的函数递归计数到
10,使用静态变量 $count 来判断何时停止:
Example #6 静态变量与递归函数
&?phpfunction&test(){&&&&static&$count&=&0;&&&&$count++;&&&&echo&$count;&&&&if&($count&&&10)&{&&&&&&&&test();&&&&}&&&&$count--;}?&
静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。
Example #7 声明静态变量
&?phpfunction&foo(){&&&&static&$int&=&0;&&&&&&&&&&//&correct&&&&static&$int&=&1+2;&&&&&&&&//&wrong&&(as&it&is&an&expression)&&&&static&$int&=&sqrt(121);&&//&wrong&&(as&it&is&an&expression&too)&&&&$int++;&&&&echo&$int;}?&
静态声明是在编译时解析的。
在函数之外使用 global 关键字不算错。可以用于在一个函数之内包含文件时。
全局和静态变量的引用
在 Zend 引擎 1 代,它驱动了 PHP4,对于变量的
定义是以的方式实现的。例如,在一个函数域内部用
语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:
以上例程会输出:
object(stdClass)(0) {
类似的行为也适用于
static 语句。引用并不是静态地存储的:
以上例程会输出:
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)(1) {
[&property&]=&
上例演示了当把一个引用赋值给一个静态变量时,第二次调用
&get_instance_ref() 函数时其值并没有被记住。
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.&?phpclass sample_class{& public function func_having_static_var($x = NULL)& {& & static $var = 0;& & if ($x === NULL)& & { return $var; }& & $var = $x;& }}$a = new sample_class();$b = new sample_class();echo $a-&func_having_static_var()."\n";echo $b-&func_having_static_var()."\n";$a-&func_having_static_var(3);echo $a-&func_having_static_var()."\n";echo $b-&func_having_static_var()."\n";?&One could expect "3 0" to be outputted, as you might think that $a-&func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:&?phpclass sample_class{ protected $var = 0; & function func($x = NULL)& { $this-&var = $x; }} ?&I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:&?phpfor($j=0; $j&3; $j++){& && if($j == 1)& & & & $a = 4;}echo $a;?&Would print 4.
Please note for using global variable in child functions:
This won't work correctly...
&?php
function foo(){
& & $f_a = 'a';
& &
& & function bar(){
& & & & global $f_a;
& & & & echo '"f_a" in BAR is: ' . $f_a . '&br /&';& }
& &
& & bar();
& & echo '"f_a" in FOO is: ' . $f_a . '&br /&';
}
?&
This will...
&?php
function foo(){
& & global $f_a;&& $f_a = 'a';
& &
& & function bar(){
& & & & global $f_a;
& & & & echo '"f_a" in BAR is: ' . $f_a . '&br /&';& }
& &
& & bar();
& & echo '"f_a" in FOO is: ' . $f_a . '&br /&';
}
?&
About more complex situation using global variables..Let's say we have two files:a.php&?php & & function a() { & & & & include("b.php"); & & }& & a();?&b.php&?php& & $b = "something";& & function b() {& & & & global $b;& & & & $b = "something new";& & }& & b();& & echo $b;?&You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:global $b;$b = "something";
Some times you need to access the same static in more than one function. There is an easy way to solve this problem:&?php& function &getStatic() {& & static $staticVar;& & return $staticVar;& }& function fooCount() {& & $ref2static = & getStatic();& & echo $ref2static++;& }& fooCount(); fooCount(); fooCount(); ?&
Took me longer than I expected to figure this out, and thought others might find it useful.I created a function (safeinclude), which I
it does processing before the file is actually included (determine full path, check it exists, etc).Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable s since the included files may or may not require global variables that are declared else where, it creates a problem.Most places (including here) seem to address this issue by something such as:&?phpglobal $myVar;$nowglobal = $GLOBALS['myVar'];?&But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)&?phpforeach ($GLOBALS as $key =& $val) { global $$key; }?&Thus, complete code looks something like the following (very basic model):&?phpfunction safeinclude($filename){& & foreach ($GLOBALS as $key =& $val) { global $$key; }& & if ($exists==true) { include("$file"); }& & return $exists;}?&In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course.& In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).Pretty simple approach that I could not
only other approach I could find was using PHP's eval().
If you have a static variable in a method of a class, all DIRECT instances of that class share that one static variable.However if you create a derived class, all DIRECT instances of that derived class will share one, but DISTINCT, copy of that static variable in method.To put it the other way around, a static variable in a method is bound to a class (not to instance). Each subclass has own copy of that variable, to be shared among its instances.To put it yet another way around, when you create a derived class, it 'seems& to' create a copy of methods from the base class, and thusly create copy of the static variables in those methods.Tested with PHP 7.0.16.&?phprequire 'libs.php';require 'setup.php';class Base {& & function test($delta = 0) {& & & & static $v = 0;& & & & $v += $delta;& & & & return $v;& & }}class Derived extends Base {}$base1 = new Base();$base2 = new Base();$derived1 = new Derived();$derived2 = new Derived();$base1-&test(3);$base2-&test(4);$derived1-&test(5);$derived2-&test(6);var_dump([ $base1-&test(), $base2-&test(), $derived1-&test(), $derived2-&test() ]);
It will be obvious for most of you: changing value of a static in one instance changes value in all instances.&?php& & class example {& & & & public static $s = 'unchanged';& & & & & & & & public function set() {& & & & & & $this::$s = 'changed';& & & & }& & }& & $o = new example;& & $p = new example;& & $o-&set();& & print "$o static: {$o::$i}\n$p static: {$p::$i}";?&Output will be:$o static: changed$p static: changed
To be vigilant, unlike Java or C++, variables declared inside blocks such as loops (for, while,...) or if's, will also be recognized and accessible outside of the block, the only valid block is the BLOCK function so:&?phpfor($j=0; $j&5; $j++){& && if($j == 1){& & & & $a = 6;& && }}echo $a;?&Would print 6.
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:&?phperror_reporting(E_ALL);$GLOB = 0;function test_references() {& & global $GLOB; $test = 1; $GLOBALS['GLOB'] = &$test; $GLOB = 2; echo "Value of global variable (via local representation set by keyword global): $GLOB &hr&";& & echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] &hr&";& & echo "Value ol local variable \$test: $test &hr&"; & & global $GLOB; echo "Value of global variable (via updated local representation set by keyword global): $GLOB &hr&";& & }test_references();echo "Value of global variable outside of function: $GLOB &hr&";?&
Sometimes a variable available in global scope is not accessible via the 'global' keyword or the $GLOBALS superglobal array. I have not been able to replicate it in original code, but it occurs when a script is run under PHPUnit.PHPUnit provides a variable "$filename" that reflects the name of the file loaded on its command line. This is available in global scope, but not in object scope. For example, the following phpUnit script (call it GlobalScope.php):&?phpprint "Global scope FILENAME [$filename]\n";class MyTestClass extends PHPUnit_Framework_TestCase {& function testMyTest() {& & global $filename;& & print "Method scope global FILENAME [$filename]\n";& & print "Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";& }}?&If you run this script via "phpunit GlobalScope.php", you will get:Global scope FILENAME [/home/ktyler/GlobalScope.php]PHPUnit 3.4.5 by Sebastian Bergmann.Method scope global FILENAME []Method scope GLOBALS[FILENAME] [].You have to -- strange as it seems -- do the following:&?php$GLOBALS["filename"]=$filename;print "Global scope FILENAME [$filename]\n";class MyTestClass extends PHPUnit_Framework_TestCase {& function testMyTest() {& & global $filename;& & print "Method scope global FILENAME [$filename]\n";& & print "Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";& }}?&By doing this, both "global" and $GLOBALS work!I don't know what it is that PHPUnit does (I know it uses Reflection) that causes a globally available variable to be implicitly unavailable via "global" or $GLOBALS. But there it is.
Static variables do not hold through inheritance.& Let class A have a function Z with a static variable.& Let class B extend class A in which function Z is not overwritten.& Two static variables will be created, one for class A and one for class B.Look at this example:&?phpclass A {& & function Z() {& & & & static $count = 0;& & & & & & & & printf("%s: %d\n", get_class($this), ++$count);& & }}class B extends A {}$a = new A();$b = new B();$a-&Z();$a-&Z();$b-&Z();$a-&Z();?&This code returns:A: 1A: 2B: 1A: 3As you can see, class A and B are using different static variables even though the same function was being used.
WARNING!& If you create a local variable in a function and then within that function assign it to a global variable by reference the object will be destroyed when the function exits and the global var will contain NOTHING!& This main sound obvious but it can be quite tricky you have a large script (like a phpgtk--) ).
&?php
function foo ()
{
&& global $testvar;
&& $localvar = new Object ();
&& $testvar = &$localvar;
}
foo ();
print_r ($testvar);&& ?&
hope this helps someone before they lose all their hair
Just a note about static properties declared at class level:class Test_Class {& static $a = 0;& public function ReturnVar(){& & return $this-&a;& }& }& $b = new Test_Class();& echo $b-&ReturnVar();Will not output "0"& because $a is declared static. Changing "static" to "public" or "private" will produce the output "0".
Take to heart this hard-won rule:& & & & Declare AT THE TOP any variable that is to be global. & & & & Both at the top of the FILE & & & & AND at the top of any FUNCTION where it appears.Why AT THE TOP? So it is sure to be declared before use. Otherwise a non-global version of the variable will be created and your code will fail.Why at the top of a FUNCTION? Because otherwise the function will refer only to its local version of the variable and your code will fail.Why at the top of the FILE? Because someday--a day that you cannot now imagine--you will want to "include" the file. And when you do, instances of the variable outside functions will not go in the global scope and your code will fail. (When the "include" is inside a calling function, variables in the included file go into the scope of the calling function.) Example file where variable $x is used outside and inside functions:& & |&!DOCTYPE html ...&& & |&html xmlns ...&& & |& & &?php global $x; ?&& & |&head& & & |& & Some html headers& & |& & &?php& & |& & & & $x = 1;& & |& & & & function bump_x() {& & |& & & & & & global $x;& & |& & & & & & $x += 1;& & |& & & & }& & |& & ?&& & |&/head&& & |&body&& & |& & More html & & |& & &?php echo $x; bump_x(); ?&& & |& & Yet more html.& & |&/body&&/html&
There're times when global variables comes in handy, like universal read only resources you just need to create once in your application and share to the rest of your scripts. But it may become quite hard to track with "variables".
writing : global $ is exactely the samething that writing : $var =& $GLOBALS['var'];It creates a reference on $GLOBALS['var'];&?php$var =1;function teste_global(){& & global $var;& & for ($var=0; $var&5; $var++){& & }}teste_global();var_dump($var);?&
I was pondering a little something regarding caching classes within a function in order to prevent the need to initiate them multiple times and not clutter the caching function's class properties with more values.I came here because I remembered something about references being lost. So I made a test to see if I could pull what I wanted to off anyway. Here's and example of how to get around the references lost issue. I hope it is helpful to someone else!&?phpclass test1{}class test2{}class test3{}function cache( $class ){& & static $loaders = array();& & & & $loaders[ $class ] = new $class();& & var_dump( $loaders );}print '&pre&';cache( 'test1' );cache( 'test2' );cache( 'test3' );?&
More on static variables:
A static variable does not retain it's value after the script's execution. Don't count on it being available from one page you'll have to use a database for that.
Second, here's a good pattern to use for declaring a static variable based on some complex logic:
&?php
& function buildStaticVariable()
& {
& & & $foo = null;
& & & return $foo;
& }
& function functionWhichUsesStaticVar()
& {
& & & static $foo = null;
& & & if($foo === null) $foo = buildStaticVariable();
& & & }
?&
Using such a pattern allows you to separate the code that creates your default static variable value from the function that uses it. Easier to maintain code is good. :)
For nested functions:This is probably obvious to most people, but global always refers to the variable in the global (top level) variable of that name, not just a variable in a higher-level scope. So this will not work:&?phpfunction a($var1){& & function b(){& & & & global $var1;& & & & echo $var1; }& & b();}a('hello');?&
Note that if you declare a variable in a function, then set it as global in that function, its value will not be retained outside of that function.& This was tripping me up for a while so I thought it would be worth noting.&?PHPfoo();echo $a; bar();echo $b; function foo() {& $a = "a"; & global $a;}function bar() {& global $b;& $b = "b";}?&
Pay attention while unsetting variables inside functions:&?php$a = "1234";echo "&pre&";echo "outer: $a\n";function testa(){& & global $a;& & echo "&& inner testa: $a\n";& & unset ($a);& & echo "&& inner testa: $a\n";}function testb(){& & global $a;& & echo "&& inner testb: $a\n";& & $a = null;& & echo "&& inner testb: $a\n";}testa();echo "outer: $a\n";testb();echo "outer: $a\n";echo "&/pre&";?&/***** Result:outer: 1234&& inner testa: 1234&& inner testa: outer: 1234&& inner testb: 1234&& inner testb: outer: ******/Took me 1 hour to find out why my variable was still there after unsetting it ...Thomas Candrian
Variable "Visibility" in PHP Object Oriented Programming is documented here:
If you need all your global variables available in a function, you can use this:
&?php
function foo() {
& extract($GLOBALS);
& }
?&
Using the global keyword inside a function to define a variable is essentially the same as passing the variable by reference as a parameter:
&?php
somefunction(){
&& global $var;
}
?&
is the same as:
&?php
somefunction(& $a) {
The advantage to using the keyword is if you have a long list of variables& needed by the function - you dont have to pass them every time you call the function.
Another way of working with a large ammount of global variables could be the following.&?php$var = "3";$smarty = new Smarty();function headers_set_404() {extract($globals);echo $var . "&br /&";print_r($smarty);}?&Regards,Droope
i found out that on any (still not found) reason the &?php static $val =NULL; ?& is not working when trying to extract the data form the $var with a while statmente.g.:&?phpfunktion get_data() {static $myarray = null;&& if($myarray == NULL) {& && $myarray = array('one','two');&& }&& while(list($key,$val) = each( $myarray ) ) {&& echo "x: $key , y: $val";&& }}?&when using foreach($myarray AS $key =& $val) { .... instad of while then i see the result!
Use the superglobal array $GLOBALS is faster than the global keyword. See:
&?php
$a=1;
$b=2;
function sum() {
& & global $a, $b;
& & $a += $b;
}
$t = microtime(true);
for($i=0; $i&1000; $i++) {
& && sum();
echo microtime(true)-$t;
echo " -- ".$a."&br&";
$a=1;
$b=2;
function sum2() {
& & $GLOBALS['a'] += $GLOBALS['b'];
}
& $t = microtime(true);
for($i=0; $i&1000; $i++) {
& && sum2();
echo microtime(true)-$t;
echo " -- ".$a."&br&";
?&
Be careful with "require", "require_once" and "include" inside functions. Even if the included file seems to define global variables, they might not be defined as such.
consider those two files:
---index.php------------------------------
&?php
function foo() {
require_once("class_person.inc");
$person= new Person();
echo $person-&my_flag; }
---class_person.inc----------------------------
&?php
$seems_global=true;
class Person {
& public $my_flag;
public function& __construct() {
&& global $seems_global;
&& $my_flag= $seems_global
---------------------------------
The reason for this behavior is quiet obvious, once you figured it out. Sadly this might not be always as easy as in this example. A solution& would be to add the line...
&?php global $seems_global; ?&
at the beginning of "class_person.inc". That makes sure you set the global-var.
&& best regards
& & tom
ps: bug search time approx. 1 hour.
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable.& For example the code:&?phpclass test {& & function z() {& & & & static $n = 0;& & & & $n++;& & & & return $n;& & }}$a =& new test();$b =& new test();print $a-&z();& print $b-&z();& ?&somewhat unexpectedly prints:12
Quick tip for beginners just to speed things up:
If you have a bunch of global variables to import into a function, it's best to put them into a named array like $variables[stuff].
When it's time to import them you j
&?php
function here() {
& $vars = $GLOBALS['variables'];
& print $vars[stuff];
This really helps with big ugly form submissions.
If you use __autoload function to load classes' definitons, beware that "static local variables are resolved at compile time" (whatever it really means) and the order in which autoloads occur may impact the semantic.For example if you have:&?phpclass Singleton{& static public function get_instance(){& && static $instance = null;& && if($instance === null){& & & & $instance = new static();& && }& && return $instance;& }}?&and two separate files A.php and B.php:class A extends Singleton{}class B extends A{}then depending on the order in which you access those two classes, and consequently, the order in which __autoload includes them, you can get strange results of calling B::get_instance() and A::get_instance().It seems that static local variables are alocated in as many copies as there are classes that inherit a method at the time of inclusion of parsing Singleton.
Using $GLOBALS inside a function you can override all references to global variables in that function with variables passed into the function as arguments. This is useful when a function does stuff to a global object but you sometimes want it to do that stuff to a different object, and you don't want to rewrite any code.For example, suppose there's a global object called $user that refers to the currently-logged-in user and a function that does stuff to that user object:&?phpfunction example_function() {& global $user;& echo $user-&id;}?&Here's how you can make that function optionally do stuff to a different user object:&?phpfunction example_function(&$user = null) {& if(!isset($user)) {& & & & && $user = $GLOBALS['user'];&& }& echo $user-&id;}?&Example usage:&?phpexample_function();& $test_user = load_user_by_id(1453);example_function($test_user); ?&
static variables are implicitly initialised to NULL if no explicit initialisation is made.&?phpfunction foo(){& static $v;& echo gettype($v);}foo();?&will echo NULL without complaining that $v is undefined.In short: "static $v;" is equivalent to "static $v =".
function f(){& & global $a; // global $a is declared, local reference is created& & $a = 'a';& // global $a is set& & unset($a); // local reference is unset, global $a remains set& & $a = 'b';& // local $a is declared and set}f();echo $a; // prints 'a'function f(){& & global $a; // global $a is declared, local reference is created& & $a = 'a';& // global $a is set& & unset($a); // local reference $a is unset, global var $a remains set& & global $a; // local reference is created again& & $a .= 'b';}f();echo $a; // prints 'ab'
If you are used to include files which declare global variables, and if you now need to include these files in a function, you will see that those globals are declared in the function's scope and so they will be lost at the end of the function.You may use something like this to solve this problem:main_file.php :&?php $a = 42;$b = 33;$c = 56;function some_function() {& & $saucisse = "saucisse";& & $jambon = "jambon";& & & & $evalt = "require_once 'anothertest_include.php';";& & $before_eval_vars = get_defined_vars();& & eval($evalt);& & $function_variable_names = array("function_variable_names" =& 0, "before_eval_vars" =& 0, "created" =& 0);& & $created = array_diff_key(get_defined_vars(), $GLOBALS, $function_variable_names, $before_eval_vars);& & foreach ($created as $created_name =& $on_sen_fiche)& & & & global $$created_name;& & extract($created);& & }some_function();print_r(get_defined_vars());?&included_file.php :&?php$included_var_one = 123;$included_var_two = 465;$included_var_three = 789;?&
Like functions, if you declare a variable in a class, then set it as global in that class, its value will not be retained outside of that class either.
&?php
class global_reference
{
& & public $val;
& &
& & public function __construct () {
& & & & global $var;
& & & & $this-&val = $var;
& & }
& &
& & public function dump_it ()
& & {
& & & & debug_zval_dump($this-&val);
& & }
& &
& & public function type_cast ()
& & {
& & & & $this-&val = (int) $this-&val;
& & }
}
$var = "x";
$obj = new global_reference();
$obj-&dump_it();
$obj-&type_cast();
echo "after change ";
$obj-&dump_it();
echo "original $var\n";
?&
The work-around is of course changing the assignment in the constructor to a reference assignment as such:
&?php
& & $this-&val = &
& & ?&
If the global you're setting is an object then no reference is necessary because of the way PHP deals with objects. If you don't want to reference to the same object however you can use the clone keyword.
&?php
global $Obj;
& & $this-&obj_copy = clone $Obj;
?&
[EDIT BY danbrown AT php DOT net:& Merged all thoughts and notes by this author into a single note.]
PHP 5.1.4 doesn't seem to care about the static keyword. It doesn't let you use $this in a static method, but you can call class methods through an instance of the class using regular -& notation. You can also call instance methods as class methods through the class itself. The documentiation here is plain wrong.
&?php
class Foo {
& public static function static_fun()
& {
& & return "This is a class method!\n";
& }
&
& public function not_static_fun()
& {
& & return "This is an instance method!\n";
& }
}
echo '&pre&';
echo "From Foo:\n";
echo Foo::static_fun();
echo Foo::not_static_fun();
echo "\n";
echo "From \$foo = new Foo():\n";
$foo = new Foo();
echo $foo-&static_fun();
echo $foo-&not_static_fun();
echo '&/pre&';
?&
You'll see the following output:
From Foo:
This is a class method!
This is an instance method!
From $foo = new Foo():
This is a class method!
This is an instance method!
If you want to access a table row using $GLOBALS, you must do it outside string delimiters or using curl braces :
&?php
$siteParams["siteName"] = "myweb";
function foo() {
$table = $GLOBALS["siteParams"]["siteName"]."articles";& echo $table; $table = "{$GLOBALS["siteParams"]["siteName"]}articles"; echo $table; $table = "$GLOBALS[siteParams][siteName]articles";& & && echo $table; $result = mysql_query("UPDATE $table ...");
}
?&
Or use global :
&?php
function foo() {
global $siteParams;
$table = "$siteParams[siteName]articles";& & & && echo $table; $result = mysql_query("UPDATE $table ...");
}
?&
Becareful where you define your global variables: This will work:&?php & $MyArray = array("Dog");& function SeeArray(){& & global $MyArray;& & if (in_array("Dog",$MyArray)){& & & foreach ($MyArray as $Element){& & & & echo "$Element &hr/&";& & & }& & }& }& SeeArray();?&while this will not:&?php & SeeArray();& $MyArray = array("Dog");& function SeeArray(){& & global $MyArray;& & if (in_array("Dog",$MyArray)){ foreach ($MyArray as $Element){& & & & echo "$Element &hr/&";& & & }& & }& }?&
I'm using PHP 4.1.1While designing a database access class, I needed a static variable that will be incremented for all instances of the class each time the class connected to the database. The obvious solution was to declare a "connection" class variable with static scope. Unfortunatly, php doesn't allow such a declaration.So I went back to defining a static variable in the connect method of my class. But it seems that the static scope is not inherited: if class "a" inherit the "db access" class, then the "connection" variable is shared among "a" instances, not among both "a" AND "db access" instances. Solution is to declare the static variable out of the db access class, and declare "global" said variable in the connect method.
If you include a file from within a function using include(), the included file inherits the function scope as its own global scope, it will not be able to see top level globals unless they are explicit in the function.
&?php
$foo = "bar";
function baz() {
& & global $foo; include("qux");
}
?&
On confusing aspect about global scope...
If you want to access a variable such as a cookie inside a function, but theres a chance it may not even be defined, you need to access it using he GLOBALS array, not by defining it as global.
This wont work correctly....
&?php
function isLoggedin()
{
global $cookie_username;
if (isset($cookie_username)
echo "blah..";
}
?&
This will..
&?php
function isLoggedin()
{
if (isset($GLOBALS["cookie_username"]))
echo "blah..";
}
?&
&?php$var = 1;function foo() {& & $var = &$GLOBALS['var'];& & var_dump($var);}function bar() {& & global $var; var_dump($var);}foo();bar();var_dump($var);?&In a function, 'global $' is to declare a local variant, and the local $var has the same reference to the global $var.&?php$var = 1;function foo() {& & global $var;& & unset($var);& & & & & & && var_dump($var);& & & & & & var_dump($GLOBALS['var']); }foo();var_dump($var);& & & & & & & & ?&&?php$var = 1;function bar() {& & global $var;& & unset($GLOBALS['var']);& & var_dump($var);& & & & & & var_dump($GLOBALS['var']); }foo();var_dump($var);& & & & & & & & ?&'unset($var);' is like 'var = NULL;'(var is a pointer) in the C language, instead of 'free(var);'
&?php$var = "hello";$func = function(){& & & if( !isset($var) ) {& & & & $var = "i was out of scope";& && }& & & & & & echo $var;};echo "$var&br /&";$func(); echo "&br /&".'$var'." never changed from $var";?&outputs :helloi was out of scope$var never changed from hello
External variables in a function
I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me:
&?php
& function makePath($root, $atom) {
& & $pos = strrpos($atom, '/');
& & if ($pos === false) {
& & & global ${'path_'.$atom};&
& & & $path = ${'path_'.$atom};
& & }
& & else {
& & & global ${'path_'.substr($atom, 0, $pos)};
& & & $path = ${'path_'.substr($atom, 0, $pos)};
& & }
& & if ($path)
& & & return ($pos === false)
& & & & ? $root.$path
& & & & : $root.$path.substr($atom, $pos + 1);
& & else
& & & return NULL;
& }
?&
Some people (including me) had a problem with defining a long GLOBAL variable list in functions (very error prone). Here is a possible solution. My program parses php file for functions, and compiles GLOBAL variable lists. Then you can just remove from the list those variables which need not be global.&?php& & $pfile=file("myfile.php4");& & & & for($i=0;$i&sizeof($pfile);$i++) {& && if(eregi("function",$pfile[$i])) {& & & list($part1,$part2)=sscanf($pfile[$i],"%s %s");& & & echo "\n\n $part1 $part2:\nGLOBAL ";& & & & & & $varlist=array();& & & $level=0; $end=$i;& & & do {& & && $lpar=explode("{",$pfile[$end]);& & && $level+=sizeof($lpar)-1;& & && $lpar=explode("}",$pfile[$end]);& & && $level-=sizeof($lpar)-1;& & && $end++;& & & } while(($end&sizeof($pfile))&&($level&0));& & & $pstr="";& & & for($j=$i;$j&=$end;$j++) $pstr.=$pfile[$j];& & & $lpar=explode("$",$pstr);& & & for($j=1;$j&sizeof($lpar);$j++) {& & & & & eregi('[a-zA-Z_][a-zA-Z0-9_]*',$lpar[$j],$cvar);& & & & $varlist[$cvar[0]]=1;& & & }& & & array_walk($varlist,'var_print');& && }& & }function var_print ($item, $key) {& && echo "$key,"; }?&
Useful function:&?phpfunction cycle($a, $b, $i=0) {& & static $switches = array();& & if (isset($switches[$i])) $switches[$i] = !$switches[$i]; else !$switches[$i] = true;& & return ($switches[$i])?$a:$b;}?&Exeample&?phpfor ($i = 1; $i&3; $i++) {& & echo $i.cycle('a', 'b').PHP_EOL;& & for ($j = 1; $j&5; $j++) {& & & & echo ' '.$j.cycle('a', 'b', 1).PHP_EOL;& & & & for ($k = 1; $k&3; $k++) {& & & & & & echo '& '.$k.cycle('c', 'd', 2).PHP_EOL;& & & & }& & }}?&
Whats good for the goose is not always good for the iterative gander. If you declare and initialize the static variable more than once inside a function ie.
&?php
function Test(){
&& static $count = 0;
&& static $count = 1;
&& static $count = 2;
&& echo $count;
}
?&
the variable will take the value of the last declaration. In this case $count=2.
But! however when you make that function recursive ie.
&?php
& function Test(){
&& static $count = 0;
&& static $count = 1;
&& static $count = 2;
&& $count++;
&& echo $count;
&& if ($count&10){
& && Test();
&& }
& }
?&
Every call to the function Test() is a differenct SCOPE and therefore the static declarations and initializations are NOT executed again. So what Im trying to say is that its OK to declare and initialize a static variable multiple times if you are in one function... but its NOT OK to declare and initialize a static variable multiple times if you call that same function multiple times. In other words the static variable is set once you LEAVE a function (even if you go back into that very same function).
Many Times Globality of variables will be the small issue, after long time I decided to use super globals.Super globals exists any where:$_SERVER, $_GET, $_POST .....Now for example:&?php$foo[] = range(0, 3);$_POST['foo'] = $foo;a(); b();$foo = $_POST['foo'];Print_r($foo);function a(){& & $_POST['foo'][] = range(4, 7);}function b(){$_POST['foo'][] = range(8, 10);}?&Note: the key must not be passed by the page via _POST method by the form, else the value will be over written
Sometimes in PHP 4 you need static variabiles in class. You can do it by referencing static variable in constructor to the class variable:&?phpclass test& {&& var $var;&& var $static_var;& & function test()& & {& & & & static $s;& & & & $this-&static_var =& $s;& & }& } $a=new test(); $a-&static_var=4; $a-&var=4;
$b=new test();
echo $b-&static_var; echo $b-&var; ?&
Interesting behavior in PHP 5.6.12 and PHP 7 RC3:&?phpclass Foo {& & public function Bar() {& & & & static $var = 0;& & & & & & & & return ++$var;& & }}$Foo_instance = new Foo;print $Foo_instance-&Bar(); print PHP_EOL;unset($Foo_instance);$Foo_instance2 = new Foo;print $Foo_instance2-&Bar(); print PHP_EOL;?&How can a 2 be printed, since we unseted the whole instance before?Consider a similar example:&?phpclass Foo {& & public static $var = 0;& & & & public static function Bar() {& & & & return ++self::$var;& & }}$Foo_instance = new Foo;print $Foo_instance-&Bar(); print PHP_EOL;unset($Foo_instance);$Foo_instance2 = new Foo;print $Foo_instance2-&Bar(); print PHP_EOL;?&No idea why is this happening.
It's possible to use a variable variable when specifying a variable as global in a function. That way your function can decide what global variable to access in run-time.
&?php
function func($varname)
{
&& global $$varname;
&& echo $$varname;
}
$hello = "hello world!";
func("hello");
?&
This will print "hello world!", and is roughly the same as passing by reference, in the case when the variable you want to pass is global. The advantage over references is that they can't have default parameters. With the method above, you can do the following.
&?php
function func($varname = FALSE)
{
&& if ($varname === FALSE)
& && echo "No variable.";
&& else
&& {
& && global $$varname;
& && echo $$varname;
&& }
}
$hello = "hello world!";
func("hello");& & & & & & & & && func();& & & & & & & & & & & & & ?&
Even if an included file return a value using return(), it's still sharing the same scope as the caller script!&?php$foo = 'aaa';$bar = include('include.php');echo($foo.' / '.$bar);?&where include.php is&?php$foo = 'bbb';return $foo;?&The output is: bbb / bbbNot: aaa / bbb
Please don't forget:
values of included (or required) file variables are NOT available in the local script if the included file resides on a remote server:
remotefile.php:
&?PHP
$paramVal=10;
?&
localfile.php:
&?PHP
include "";
echo "remote-value= $paramVal";
?&
Will not work (!!)
Alright, so you can't set a static variable with a reference.However, you can set a static variable to an array with an element that is a reference:&?phpclass myReference {& & function getOrSet($array = null) {& & & & static $myValue;& & & & if (!$array) {& & & & & & return $myValue[0];& && }& & & & $myValue = $array;& & & & & static $myValue;& & }}$static = "Dummy";$dummy = new myReference;$dummy-&getOrSet(array(&$static));$static = "Test";print $dummy-&getOrSet();?&

我要回帖

更多关于 js中输出php变量 的文章

 

随机推荐