我想Model
在 PHP 中获取类的属性名称。在java中我可以这样做:
模型.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;
}
}
主.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 中做到这一点?
模型.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;
}
}
?>
索引.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";
}
?>