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

6 篇文章 0 订阅

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

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在类外引用,自然在类外修改更为合理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tajang

感谢投喂

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值