PHP 静态关键字static

来源:4-3 Static(静态)关键字-PHP面向对象编程

qq_慕瓜3288387

2020-12-07 18:13

<?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


写回答 关注

1回答

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

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

PHP面向对象编程

从容应对面试官的知识宝典,带你握面向对象的最重要的核心能力

70153 学习 · 361 问题

查看课程

相似问题