php--静的変数
2544 ワード
一般的な関数内の変数は、局所変数などの関数の終了後に解放されますが、静的変数は解放されません.次にこの関数を呼び出すと、変数の値が残ります.静的変数の基本的な使い方1.クラスに静的変数[アクセス修飾子]static$変数名を定義します. 2. 静的変数へのアクセス方法クラスでアクセスする方法self::$静的変数名、クラス名:$静的変数名クラス外でアクセスする場合:メソッドクラス名:$静的変数名
class Child{
public $name;
// $nums
public static $nums=0;
function __construct($name){
$this->name=$name;
}
public function join_game(){
//self::$nums
self::$nums+=1;
echo $this->name." ";
}
}
//
$child1=new Child(" ");
$child1->join_game();
$child2=new Child(" ");
$child2->join_game();
$child3=new Child(" ");
$child3->join_game();
//
echo "<br/> ".Child::$nums;