Clean Blog

海阔凭鱼跃,天高任鸟飞

PHP反射机制Reflection

<?php

class Cart
{
    const PRICE_BUTTER = 1.00;
    const PRICE_MILK = 3.00;
    const PRICE_EGGS = 6.95;

    public $products = array();
    protected $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }

    public function getTotal($tax)
    {
        $total = 0.00;

        array_walk($this->products, function ($quantity, $product) use ($tax, &$total) {
            echo $quantity, $product . "\n\n";
            $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                strtoupper($product));
            $total += ($pricePerItem * $quantity) * ($tax + 1.0);
        });
        return round($total, 2);;
    }
}

$cart = new Cart("XX");

// 创建反射对象
$reflect = new ReflectionObject($cart);
echo "获取对象方法列表:\n";
foreach ($reflect->getMethods() as $method) {
    echo "method name: ".$method->getName()."\n";
}

echo "\n获取具体某个对象属性:".$reflect->getProperty('products')->getName()."\n";

echo "\n获取对象属性列表:\n";
foreach ($reflect->getProperties() as $property) {
    echo "property name: ".$property->getName()."\n";
}

echo "\n获取默认的属性值:\n";
print_r($reflect->getDefaultProperties());

echo "获取定义类的文件名(全路径):\n";
echo $reflect->getFileName();

echo "\n获取类名:\n";
echo $reflect->getName();

echo "\n获取类的短名,就是不含命名空间(namespace)的那一部分: \n";
echo $reflect->getShortName();

//反射获取类的原型
$reflection = new ReflectionClass(Cart::class);
$className = $reflection->getName();

结果

D:\wnmp\php-7.0.21\php.exe F:\workSpace\mySelf\Test_mp\de.php
获取对象方法列表:
method name: __construct
method name: add
method name: getTotal

获取具体某个对象属性:products

获取对象属性列表:
property name: products
property name: a

获取默认的属性值:
Array
(
    [products] => Array
        (
        )

    [a] => 
)
获取定义类的文件名(全路径):
F:\workSpace\mySelf\Test_mp\de.php
获取类名:
Cart
获取类的短名,就是不含命名空间(namespace)的那一部分: 
Cart