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;
}
}
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";
}
?>