Source Code Fundamentals: Variables



Local Variables

Except for function parameters, a local variable is never defined explicitly; instead, it is created when it is first assigned a value. A local variable can be assigned to as a parameter in the parameter list of a function definition or inside any compound statement. It has function scope.

Consider the following example:

function do_it(bool $p1): void {  // assigned the value true when called
  $count = 10;
  if ($p1) {
    $message = "Can't open master file.";

Here, the parameter $p1 (which is a local variable) takes on the value true when do_it is called. The local variables $count and $message take on the type of the respective value being assigned to them.

Consider the following example:

function f(): void {
  $lv = 1;
  echo "\$lv = $lv\n";

function main(): void {
  for ($i = 1; $i <= 3; ++$i)
$lv = 1
$lv = 1
$lv = 1

As you can see, the value of the local variable $lv is not preserved between the function calls, so this function f outputs "$lv = 1" each time.

Array Elements

An array is created via a vec-literal, a dict-literal, a set-literal, using array, or the array-creation operator. At the same time, one or more elements may be created for that array. New elements are inserted into an existing array via the simple-assignment operator in conjunction with the subscript [] operator.

The scope of an array element is the same as the scope of that array's name.

$colors1 = vec["green", "yellow"];   // create a vec of two elements
$colors1[] = "blue";                 // add element 2 with value "blue"
$colors2 = dict[];                   // create an empty dict
$colors2[4] = "black";               // create element 4 with value "black"
$colors3 = array();                  // create empty array
$colors3 = ["red", "white", "blue"]; // create array<string> with 3 elements
$colors3[] = "green";                // insert a new element 3

Instance Properties


Static Properties


Class and Interface Constants


本节由 Y!an 翻译