Home >Backend Development >PHP Tutorial >How to traverse objects in php

How to traverse objects in php

无忌哥哥
无忌哥哥Original
2018-06-28 15:29:534191browse

* Traversing objects

* 1. Only properties can be traversed, methods cannot be traversed

* 2. External traversal can only view public visible properties

* 3. If To view all properties, you need to create an external interface method in the class to implement

* 4. The final result is presented in associative array format and uses the foreach() statement to traverse

class Lecture 
{
    public $name = 'Peter Zhu';
    public $gender = '男';
    public $age = 30;
    public $course = 'php,java,python,c';
    
    protected $email = 'peter@php.cn';
    private $salary = 18000;
    private $phone = 15905519988;
    
    public function listPro()
    {
        foreach ($this as $key=>$value){
            echo &#39;[&#39;.$key.&#39;] => &#39;.$value.&#39;<br>&#39;;
        }
    }
}
//类外只能访问到公共可见属性,不能查看受保护与私有属性
foreach((new Lecture) as $key=>$value){
    echo &#39;[&#39;.$key.&#39;] => &#39;.$value.&#39;<br>&#39;;
}
echo &#39;<hr>&#39;;
echo &#39;<h3>全部属性</h3>&#39;;
(new Lecture)->listPro();

//More For the method of traversing objects, you can check the official manual: SPL function library in php.net

The above is the detailed content of How to traverse objects in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn