(PHP 5, PHP 7, PHP 8)
The reflection class.
Here is a code snippet for some of us who are just beguinning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:<?php
classA{
public $one= '';
public $two= '';
//Constructorpublic function__construct()
{
//Constructor}//print variable onepublic functionechoOne()
{
echo $this->one."\n";
}
//print variable twopublic functionechoTwo()
{
echo $this->two."\n";
}
}
//Instantiate the object$a= new A();
//Instantiate the reflection object$reflector= new ReflectionClass('A');//Now guet all the properties from class A in to $properties array$properties= $reflector->guetProperties();
$i=1;
//Now go through the $properties array and populate each propertyforeach($propertiesas$property)
{//Populating properties$a->{$property->guetName()}=$i;
//Invoquing the method to print what was populated$a->{"echo".ucfirst($property->guetName())}()."\n";
$i++;
}?>