天天看點

靜态變量和靜态方法

全局變量

  • 在程式中都可以使用的變量稱為全局變量。
  • 案例
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<body>
<?php
	global $num;
	function calc1(){
		global $num;
		$num=20;
		echo $num."<br/>";
	}
	function calc2(){
		$num=10;
		echo $num."<br/>";
	}	
	calc1();
	calc2();
	echo $num."<br/>";
?>
</body>
</html>
           
靜态變量和靜态方法

靜态變量

  • 在類中定義靜态變量。
  • 靜态變量屬于類,而非對象。
修飾符 static $變量名;
//修飾符 static $變量名=初始值;
           
  • 通路靜态變量
    • 類中通路: (1)self::$變量名(2)類名::$變量名
    • 類外通路: 類名::$變量名
  • 案例
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<body>
<?php
	class Person{
		public function __construct($iname,$isex,$iage){
			$this->name=$iname;
			$this->sex=$isex;
			$this->age=$iage;
			//類中使用靜态變量
			++self::$num;
		}
		public function showInfo(){
			echo $this->name." ".$this->sex." ".$this->age."<br/>";
		}
		public function __destruct(){
			echo "析構函數<br/>";
		}
		public $name;
		public $sex;
		public $age;
		//定義靜态變量
		public static $num=0;
	}
	
	
	$person1=new Person("張三","woman",18);
	$person2=new Person("李四","man",19);
	//類外使用靜态變量
	echo Person::$num."<br/>";
?>
</body>
</html>
           

靜态方法

  • 靜态方法(類方法),屬于所有對象執行個體的,基本文法:
修飾符 static 方法名(){
	...
}
           
  • 靜态方法不能通路非靜态屬性(成員變量)。
  • 普通成員方法通路普通屬性和靜态屬性。
  • 靜态方法通路靜态屬性。
  • 類内通路
類名::類方法名(參數)
self::類方法名(參數)
           
  • 類外通路
類名::類方法名(參數)
$對象名->類方法名(參數)
           
  • 案例
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<body>
<?php
	class Person{
		public function __construct($iname,$isex,$iage){
			$this->name=$iname;
			$this->sex=$isex;
			$this->age=$iage;
		}
		public function showInfo(){
			echo $this->name." ".$this->sex." ".$this->age."<br/>";
		}
		public static function setNum(){
			//類中使用靜态變量
			++self::$num;
		}
		public function __destruct(){
			echo "析構函數<br/>";
		}
		public $name;
		public $sex;
		public $age;
		//定義靜态變量
		public static $num=0;
	}
	
	
	$person1=new Person("張三","woman",18);
	//在類外使用靜态函數
	$person1->setNum();
	$person2=new Person("李四","man",19);
	//在類外使用靜态函數
	Person::setNum();
	echo Person::$num."<br/>";
?>
</body>
</html>