在PHP中获取Model属性


Get Model property in PHP

我想在PHP中获得Model类的属性名。在java中,我可以像这样做:

Model.java

public class Model {
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Main.java

import java.lang.reflect.Field;
public class Main {
    public static void main(String[] args) {
        for(Field field : Model.class.getDeclaredFields()) {
            System.out.println(field.getName());
        }
    }
}

它将打印:

id
name

我如何在PHP中做到这一点?

Model.php

<?php 
    class Model {
        private $id;
        private $name;
        public function __get($property) {
            if(property_exists($this, $property))
                return $this->$property;
        }
        public function __set($property, $value) {
            if(property_exists($this, $property))
                $this->$property = $value;
            return $this;
        }
    }
?>

index.php

<?php
    # How to loop and get the property of the model like in Main.java above?
?>

更新解决方案

解决方案1:

<?php
    include 'Model.php';
    $model = new Model();
    $reflect = new ReflectionClass($model);
    $props   = $reflect->getProperties(ReflectionProperty::IS_PRIVATE);
    foreach ($props as $prop) {
        print $prop->getName() . "'n";
    }
?>

解决方案2:

<?php
    include 'Model.php';
    $rc = new ReflectionClass('Model');
    $properties = $rc->getProperties();
    foreach($properties as $reflectionProperty) {
        echo $reflectionProperty->name . "'n";
    }
?>

我相信你在找ReflectionClass::getProperties

可在PHP中使用>=5

也可提供get_object_vars

可在PHP 4&5

两个文档页面都列出了示例,但如果您在更新问题时遇到问题,或者针对您遇到的特定问题提出不同的问题(并显示您尝试过的内容)。

您可以使用PHP内置的反射功能,就像在Java中一样。

<?php
$rc = new ReflectionClass('Model');
$properties = $rc->getProperties();
foreach($properties as $reflectionProperty)
{
    echo $reflectionProperty->name;
}

请参阅此处的PHP反射手册。