php 反射例子
<?php
class Printer
{
}
class Student
{
private $name;
private $year;
public function __construct($name, $year)
{
$this->name = $name;
$this->year = $year;
}
public function getValue()
{
return $this->name;
}
public function setBase(Printer $printer, $name, $year = 10)
{
$this->name = $name;
$this->year = $year;
}
}
$refl_class = new ReflectionClass(Student::class);
$object = $refl_class->newInstanceArgs(["obama", 100]);
echo get_class($object) . "\n";
echo $object->getValue();
$refl_method = $refl_class->getMethod("setBase");
echo get_class($refl_method) . "\n";
$parameters = $refl_method->getParameters();
print_r($parameters);
foreach ($parameters as $parameter) {
echo $parameter->getName() . "\n";
print_r($parameter->getClass() );
if ($parameter->getClass() != null) {
echo $parameter->getClass()->getName() . "\n";
}
if ($parameter->isDefaultValueAvailable()) {
echo $parameter->getDefaultValue() . "\n";
}
echo '===';
}
echo "\n";
function display($a, $b, Printer $printer)
{
echo "called" . "\n";
}
$refl_function = new ReflectionFunction("display");
$parameters = $refl_function->getParameters();
foreach ($parameters as $parameter) {
echo $parameter->getName() . "\n";
if ($parameter->getClass() != null) {
echo $parameter->getClass()->getName() . "\n";
}
if ($parameter->isDefaultValueAvailable()) {
echo $parameter->getDefaultValue() . "\n";
}
}
原文 http://www.php100.com/9/20/22/87470.html
来源:oschina
链接:https://my.oschina.net/shunshun/blog/3217605