问答详情
源自:4-3 Static(静态)关键字-PHP面向对象编程

PHP 静态关键字static

<?php
class glass{
	public $name;
	public $height;
	public $weight;
	public $color;


	public static $capacity;//定义静态变量capacity 容量




	function __construct($name,$height,$weight,$color,$capacity)
	// 问题1:构造函数前面是function,不是public


	{
		$this->name=$name;
		$this->height=$height;
		$this->weight=$weight;
		$this->color=$color;
		self::$capacity=$capacity;


		echo $this->name."杯子的高度为"."$height"."\n"."$this->name"."杯子的颜色为"."$color"."\n"."$this->name"."杯子的容量为"."$capacity"."\n"."\n";
	}


	function __destruct(){
		echo "销毁".$this->name."杯子"."\n";
	}


	public static function ChangeCapacity($newcapacity){
		self::$capacity=$newcapacity;
		// echo "$this->name"."$newcapacity"."\n";
	}
}






$glass1=new glass("num1","500mm","100mm","蓝色","500ml");
// $glass2=new glass("num2","300mm","500mm","黑色","750ml");


// $glass1->ChangeCapacity("900ml");




//问题2:修改静态成员参数值的方法
// 应使用 	类名::成员参数("参数值");
//输出 		echo 类名::$成员参数;
glass::ChangeCapacity("123");
echo glass::$capacity."\n";
$glass3=new glass("num3","100mm","100mm","白色","520ml");
?>

在下面修改了glass类中capacity参数为123,但是后面再次实例化对象后,输出的$capacity值仍为定义的"520ml",而不是修改后的值:123


提问者:qq_慕瓜3288387 2020-12-07 18:13

个回答

  • 慕村449674
    2020-12-09 16:28:02

    http://img4.mukewang.com/5fd0899500011ebd02550039.jpg你这里这样写相当于给静态变量重新赋值,你想要的效果是构造函数的参数值等于静态变量的值,应该写成   $capacity = self::$capacity;