I need to refactor this code to not use a parameter when using the “save()” method.
The code is:
Person.php
class Person {
public $name;
public $age;
public $country;
public function save($object) {
$api = new ReflectionClass($object);
foreach($api->getProperties() as $propertie)
{
print $propertie->getName() . " - " . $propertie->getValue($object) . " | ";
}
}
}
?>
Example_usage.php
include_once('person.php');
$p = new Person();
$p->name = 'Mary';
$p->age = '28';
$p->country = 'Italy';
$p->save($p);
?>
My question. How can I use the “save()” method like this:
$p->save();
It is possible to pass the $p object in other way than passing the parameter in the “save()” method?
You shouldn’t use
ReflectionClassfor this purpose.If you would like to get each variable name together with its value, it’s as easy this: