如何修改 类名::静态变量?

好久没更新了,其中经历了备战省赛,重装电脑,换服务器,重新搭建博客等一系列事,受到许多技术大牛的指点,而且新人太厉害了,卷卷卷!

Geek Challenge 2021有一道BabyPOP,这个题其实不难的,但我知识点掌握太少了,题刷的还是少。类名::静态变量 这种调用方式遇到过,但只是利用它,而没想过改变它。

如何改变类名::静态变量?

我们先来做几个测试

1.无操作

<?php
class A{
    
    
	public  static $x=false;
	public function test(){
    
    
        var_dump(A::$x);
        var_dump($this->x);
	}
}
$s=new A();
$s->test();

此时A:: x 为 f a l s e , x为false, xfalsethis->x为NULL

2.使用construct方法改变$this->x值

<?php
class A{
    
    
	public  static $x=false;
    public function __construct(){
    
    
        $this->x=true;
    }
	public function test(){
    
    
        var_dump(A::$x);
        var_dump($this->x);
	}
}
$s=new A();
$s->test();

此时A:: x 为 f a l s e , x为false, xfalsethis->x为true,可见使用construct方法只能改变 t h i s − > x ,对 A : : this->x,对A:: this>x,对A::x无效

3.反序列化改变$this->x的值

先生成一个序列化字符串

<?php
class A{
    
    
	public  static $x=false;
    public function __construct(){
    
    
        $this->x=true;
    }
}
echo serialize(new A());

序列化字符串:O:1:"A":1:{s:1:"x";b:1;}

传入字符串

<?php
class A{
    
    
	public  static $x=false;
	public function test(){
    
    
        var_dump(A::$x);
        var_dump($this->x);
	}
}
$s=unserialize('O:1:"A":1:{s:1:"x";b:1;}');
$s->test();

此时A:: x 为 f a l s e , x为false, xfalsethis->x为true,可见使用反序列化方法只能改变 t h i s − > x ,对 A : : this->x,对A:: this>x,对A::x无效

4.在其他类中改变A::$x的值

<?php
class A{
    
    
	public  static $x=false;
	public function test(){
    
    
        var_dump(A::$x);
        var_dump($this->x);
	}
}

class B{
    
    
    public function __construct(){
    
    
        A::$x=true;
        $p=new A();
        $p->test();
    }
}
$s=new B();

此时A:: x 为 t r u e , x为true, xtruethis->x因为没赋值所以为NULL若是想修改,参考测试2在A类里可以直接改

此时我们找到了修改 类名::静态变量 的方法,其实也不难想到, t h i s − > x 就是在类内引用,所以在类内改;而 A : : this->x就是在类内引用,所以在类内改;而A:: this>x就是在类内引用,所以在类内改;而A::x在类外引用,自然在类外修改更为合理。

猜你喜欢

转载自blog.csdn.net/qq_45619909/article/details/128947086