duanju7199 2013-01-29 21:48
浏览 36

调用PHP方法,同时忽略参数的类型提示

Given:

class Foo {
    private $bar;

    public function setBar(Bar $bar) {
         $this->bar = $bar;
    }
}

Is there any way to call setBar() with a parameter that is not an instance of Bar?

$proxy = new Proxy();

$foo = new Foo();
$foo->setBar($proxy);

// with
class Proxy  {
}

The idea is to inject a proxy object instead of a Bar instance. The Proxy class is generic (in a dependency injection framework) and cannot be made to implement/extend Bar.


The Reflection API doesn't seem to provide anything making that possible. I'm looking to do that without using a PHP extension (standard PHP install > 5.3) (and I'm trying to leave eval alone if possible).

Note: yes this is weird stuff, I'm expecting comments about that, but please leave the "answers" for actual answers to the question. This is not intended to be production code.

  • 写回答

3条回答 默认 最新

  • douji9518 2013-01-29 23:05
    关注

    Is it a requirement to call setBar(), or can you settle with just setting the private $bar property?

    The latter is possible with ReflectionProperty::setAccessible, then you can assign anything to the property you want, as if it was a public property. It won't actually turn it into public, but it will be modifiable through the reflection classes.

    AFAIK, the former is not possible without creating temporary classes in strings, then eval()ing those, this is what the mocking frameworks do.

    评论

报告相同问题?