stevenwadejr/exposure

Exposure 作为对象上受保护的和私有属性及方法的代理。

0.3.0 2015-08-31 19:35 UTC

This package is auto-updated.

Last update: 2024-09-20 06:14:34 UTC


README

"让你的私有公开"。

你是否曾经需要访问私有/受保护的对象属性或方法?当然,它们是私有/受保护的,有它的原因... 但有时候你真的 需要 它们。

Exposure 暴露 私有和受保护的属性和方法,同时允许在对象 实例化之后 添加新的方法。

安装

通过 Composer

composer require stevenwadejr/exposure

0.3.0 版本的新特性是什么?

你现在可以公开你的对象 并且 享受类型提示。Exposure 现在附带一个工厂,用于创建扩展你的封闭类的 Exposure 的新实例。

示例

use StevenWadeJr\Exposure\Factory;

class CantTouchThis
{
    private $privateParty = 'This is private';
}

$exposed = Factory::expose(new CantTouchThis);
echo $exposed->privateParty; // outputs 'This is private'
var_dump($exposed instanceof CantTouchThis); // outputs 'true'

示例

<?php
use StevenWadeJr\Exposure\Exposure;

class CantTouchThis
{
    public $publicProperty = 'This is public';

    protected $protectedProperty = 'This is protected';

    private $privateProperty = 'This is private';

    public function publicMethod()
    {
        return 'This is a public method';
    }

    protected function protectedMethod()
    {
        return 'This is a protected method';
    }

    private function privateMethod()
    {
        return 'This is a private method';
    }
}

$exposure = new Exposure(new CantTouchThis);

访问公共属性和方法

echo $exposure->publicProperty; // outputs 'This is public'
echo $exposure->publicMethod(); // outputs 'This is a public method'

无法访问的属性和方法

echo $exposure->privateProperty; // outputs 'This is private'
echo $exposure->protectedMethod(); // outputs 'This is a protected method'

重写受保护的属性

$exposure->protectedProperty = 'New protected property';
echo $exposure->protectedProperty; // outputs 'New protected property'

向对象添加新方法

$exposure->__methods('setProtectedProperty', function()
{
    $this->protectedProperty = 'Whoops, I touched this!';
});
$exposure->setProtectedProperty();
echo $exposure->protectedProperty; // outputs 'Whoops, I touched this!'

为什么?

显然,尽可能遵循 开放/封闭原则,在极少情况下,你应该实际使用这个类,但有时候确实如此。

用途

生产?请不要。测试?当然!