ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### foreach方法 所以,对象其实就是有“生命力”的数组 . **前提是这些属性是public,如果是私有的或者是受保护的,将无法遍历**. ~~~ class Person{ public $name; public $age; public $height; public $weight; public function __construct($name, $age, $height, $weight) { $this->name = $name; $this->age = $age; $this->height = $height; $this->weight = $weight; } } $p = new Person('jack',20,150,176); foreach($p as $key => $value){ echo $key.'-->'.$value; } ~~~ ~~~ name-->jack age-->20 height-->150 weight-->176 ~~~ ### 定义方法遍历非public属性 ~~~ class Person{ private $name; private $age; private $height; private $weight; public function __construct($name, $age, $height, $weight) { $this->name = $name; $this->age = $age; $this->height = $height; $this->weight = $weight; } public function myForeach() { foreach($this as $key => $value){ echo $key . '-->' . $value; } } } $p = new Person('jack', 20, 150, 176); $p->myForeach(); ~~~ ~~~ name-->jack age-->20 height-->150 weight-->176 ~~~ ### 对象自定义遍历