浅析PHP类中的静态方法以及静态属性

时间:2021-05-16 19:34:01
  • 静态属性有两种,局部静态跟全局静态,局部静态是只在函数作用域内有用,外部引用时会报错,全局静态则在函数内外部都可以引用且改变值。静态属性只会初始化一次,然后就会存在一块固定的内存块里。
function test(){
static $var = 5; //static $var = 1+1;就会报错
$var++;
echo $var . ' ';
}
test(); //2
test(); //3
test(); //4
echo $var; //报错:Notice: Undefined variable: var

function static_global(){
global $glo;
$glo++;
echo $glo.'<br>';
}

static_global(); //1
static_global(); //2
static_global(); //3
echo $glo . '<br>'; //3
  • 关于静态方法与非静态方法之间调用的注意事项,下面举例说明:
class Banji{
public static $nums = 0;

public $name = '';

public function __construct($name){
$this->name = $name;
self::$nums++;
}

public function nums(){
echo self::$nums;
echo '<br>';
echo $this->name;
echo '<br>';
}

public static function test(){
echo self::$nums;
echo '<br>';
}

public static function test1(){
echo self::$nums;
echo '<br>';
echo $this->name;
echo '<br>';
}

public static function test2(){
self::nums();
}

public static function test3(){
$this->nums();
}


public function test4(){
self::test();
}
}

$student = new Banji('Susunma');

$student->nums(); //1 Susunma

$student = new Banji('Susunma1');

$student->nums(); //2 Susunma1

$student = new Banji('Susunma2');

$student->nums(); //3 Susunma2

$student->test(); //3

$student->test1(); //Fatal error: Uncaught Error: Using $this when not in object context 即静态方法中不能调用非静态属性

Banji::test(); //3

Banji::test1(); //Fatal error: Uncaught Error: Using $this when not in object context

$student->test2(); //Deprecated: Non-static method Banji::nums() should not be called statically 非静态方法中不能以静态方式调用

$student->test3(); //Fatal error: Uncaught Error: Using $this when not in object context 即静态方法中不能调用非静态方法

$student->test4(); //3 即非静态方法可以访问静态方法以及静态属性