有人可以为我清理静态变量吗?

Using PHP here, I decided to read through the manual chapter by chapter and learn new things. So now I've discovered static variables, which seem like an awesome concept, but the way I understand it is:

Static variables are set once and only once per load of the script. They can be changed and incremented but not actually re-set. Usually used in functions to set a value and not have to initialize that variable every time the function runs.

<?php

function count2( $inputNum ) {
    static $a = $inputNum;
    echo $a++; //Echo and then increment.
}

for ( $i = 0; $i < 10; $i++ ) {
    count2(50);
}

?>

I'd expect this to start the static $a var at 50, and increment 11 times. How come I get an error?

The static variable cannot be initialized with another variable, whose value is not known until runtime. You must initialize it with a value known at compile time.

function count2($inputNum) {
  // Initialize only once to an integer (non variable, non-expression)
  static $a = 0;
  if ($a === 0) {
    // If $a is still 0, set it to $inputNum
    $a = $inputNum;
  }
  echo $a++;
}

// First run outputs 25
count2(25);
// 25
// Subsequent runs increment
count2(25);
// 26
count2(25);
// 27

Relevant documentation...

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

I think you missed that part from the docs (emphasize mine) :)

Few problems off the bat:

  • You can only declare a static var once. Your syntax clobbers it over and over by calling count2() 10 times.
  • You can't use the ++ operator because you can't change a static var
  • Not using define and constant

Perhaps try something like:

<?php
error_reporting(E_ALL);

/* setup */

function set( $input ) {
    define( 'A', $input );
}
function tick() {
    echo constant( 'A' ) . "
";
}

/* run */

set( 50 );
for($i=0; $i<10; $i++){
    tick();
}

?>

This will output:

$ php test.php 
50
50
50
50
50
50
50
50
50
50