首页 > 代码库 > PHP之OOP——foreach

PHP之OOP——foreach

 1 <?php
 2     
 3     //对象的遍历,所用的对象都存储在 php内部的一个 叫 stdclass 类的集合中
 4     header("content-Type:text/html;charset=utf-8");
 5 class Student{
 6     public $name;
 7     public $gender;
 8     private $_age;
 9 
10     //声明构造方法
11     public function __construct($name, $gender, $_age){
12         $this->name = $name;
13         $this->gender = $gender;
14         $this->$_age = $_age;
15     }
16 
17 }
18 
19 $s  = new Student(‘徐进‘,‘male‘,‘20‘);
20 
21 // var_dump($s);
22 foreach ($s as $key => $value) {
23     var_dump($key,$value);
24 }
25 
26 echo "<hr>";
27 //把对象强制转换城数组
28 
29 $arr = array(‘name‘=>‘xujin‘,‘age‘=>‘20‘,‘gender‘=>‘male‘);
30 $arr1 = (object) $arr;
31 foreach ($$arr1 as $key => $value) {
32 
33     var_dump($key,$value);
34 }

 

PHP之OOP——foreach