Home > Backend Development > PHP Tutorial > PHP object-oriented-code sharing for object traversal

PHP object-oriented-code sharing for object traversal

黄舟
Release: 2023-03-06 22:06:02
Original
1457 people have browsed it

The traversal of objects is the same as the traversal of arrays. The traversal of objects refers to the traversal of instanceproperties.
 
The attributes traversed below are "accessible attributes" in this scope (access permissions must be considered).

<?phpclass A{
    public $p1 = 1;    
    protected $p2 = 2;    
    private $p3 = 3;    
    static $p4 = 4;
}$obj1 = new A();foreach($obj1 as $key => $value){//$key表示对象的属性,$value是其对应的值
    echo "<br />属性$key :" . $value;   
}?>
Copy after login

Run result:

属性p1 :1
Copy after login

It can be seen that only public modified properties can be traversed, so how to traverse all properties of an object? Just write a traversal method inside the class.

<?phpclass A{
    public $p1 = 1;    
    protected $p2 = 2;    
    private $p3 = 3;    
    static $p4 = 4;    //静态属性

    function showAllProperties(){
        foreach($this as $key => $value){            
        echo "<br />属性$key :$value";  
        }   
    }
}$obj1 = new A();$obj1->showAllProperties();?>
Copy after login

Run result:

属性p1 :1
属性p2 :2
属性p3 :3
Copy after login

But static properties do not belong to the object, so they cannot be traversed.

The above is the detailed content of PHP object-oriented-code sharing for object traversal. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template