Log in / create account | Login with OpenID
DocForge
An Open Wiki For Software Developers

PHP/Variable

From DocForge

< PHP

PHP variables are case-sensitive labels preceded by a dollar sign ("$"). Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore.

Being a loosely typed language, PHP variables do not need to be declared with a type before they are first used. Variables can be assigned a value of any type at any time.

One special variable, $this, is defined by PHP and cannot be reassigned. It's used by objects to refer to themselves.

Scope [edit]

Within a function a variable has local scope by default. Variables defined outside a function or class definition are in global scope. To use a global variable within a function, the global keyword must be used.

Static [edit]

A static variable is one which retains its value across function calls. Instead of being instantiated upon each call to a function, a static variable will still have the value it was last assigned when the function was last called.

A static variable can be assigned a default value when declared.

For example:

function foo() {
  static $counter = 0;
  $non_static = 0;
  
  $counter++;
  $non_static++;
  
  echo 'counter: ', $counter, ', non-static: ', $non_static, "\n";
}
 
foo();
foo();
foo();
 
// Output:
// counter: 1, non-static: 1
// counter: 2, non-static: 1
// counter: 3, non-static: 1

See Also [edit]