I want to get property name of Model class in PHP. In java I can do like this one:
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());
}
}
}
It will print:
id
name
How can I do that in 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?
?>
Update Solution
Solution 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";
}
?>
Solution 2:
<?php
include 'Model.php';
$rc = new ReflectionClass('Model');
$properties = $rc->getProperties();
foreach($properties as $reflectionProperty) {
echo $reflectionProperty->name . "\n";
}
?>
I believe you’re looking for
ReflectionClass::getProperties?Available in PHP >= 5
Also available,
get_object_varsAvailable in PHP 4 & 5
Both documentation pages list examples, but if you have trouble update your question or ask a different question with the specific problem you’re having (and show what you’ve tried).