php笔记(16)遍历对象

对象的遍历和数组差不多,因为属性有访问权限设置,所以外部访问和内部访问结果不一样,还有静态属性等不同

//遍历对象
class Demo{
	public $name;
	public $age;
	public static $sex;
	protected $birthday;
	private $habit;
	public function __construct($name,$age,$sex,$birthday,$habit){
		$this->name=$name;
		$this->age=$age;
		self::$sex=$sex;
		$this->birthday=$birthday;
		$this->habit=$habit;
	}
	//内部遍历
	public function query(){
		foreach ($this as $key => $value) {
			echo $key.'=>'.$value.'<br>';
		}
	}
}
//外部遍历

$demo=new Demo('小明',20,'male','20000202','跑步');
//公共属性只有name和age
foreach ($demo as $key => $value) {
	echo $key.'=>'.$value.'<br>';
}
//name=>小明 age=>20

//调用内部遍历方法query();sex是静态属性所以对象无法访问
$demo->query();
//name=>小明 age=>20 birthday=>20000202 habit=>跑步

//访问静态属性sex
echo Demo::$sex;//male

猜你喜欢

转载自blog.csdn.net/weixin_42881256/article/details/82823699