版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/84291353
全局变量
- 在程序中都可以使用的变量称为全局变量。
- 案例
<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>