我想在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";
}
?>
答案 0 :(得分:3)
我相信您正在寻找ReflectionClass::getProperties
?
以PHP格式提供&gt; = 5
同样可用,get_object_vars
提供PHP 4&amp; 5
两个文档页面都列出了示例,但如果您无法更新问题或针对您遇到的具体问题提出不同的问题(并显示您尝试过的内容)。
答案 1 :(得分:3)
您可以使用PHP的内置Reflection功能,就像在Java中一样。
<?php
$rc = new ReflectionClass('Model');
$properties = $rc->getProperties();
foreach($properties as $reflectionProperty)
{
echo $reflectionProperty->name;
}
请参阅reflection here上的PHP手册。