2

Anyone know if it's possible in PHP to force a class to extend or implement an interface without the child class having to declare it?

Example:

interface Requirements
{
    public function __construct();
    public function kittens();
}

class DingleBerry
{
    public function __construct()
    {
        // yadda yadda yadda    
    }
}

// Example of my initial hope
// of what you could do

$kittens = new DingleBerry implements Requirements;

Obviously that doesn't work, but I need a way of loading in classes that have no predetermined knowledge of the interface requirements but are forced to abide by them.

My overall goal is to check to see if the class implements the Requirements BEFORE its loaded and it's constructor is called.

So I CANNOT use this:

interface Requirements
{
    public function __construct();
    public function kittens();
}

class DingleBerry
{
    public function __construct()
    {
        // DO BAD STUFF (i.e. eat your soul)
    }
}

// Example of what I CANNOT
// do.

$kittens = new DingleBerry;

if( !($kittens instanceof Requirements) )
{
    // eat pizza.    
}

Because then DingleBerry's constructor is called before I can check if it implements the Requirements. Dig?

4

2 回答 2

2

如果不使用第三方扩展(例如:runkit),您不能修改已经声明的类或接口定义。

Runkit 有一个runkit_class_adopt函数可以满足这个需求。不幸的是,我无法测试它,因为 PECL 版本无法在我的机器上编译。

对于您问题的第一部分,您可以检查一个类是否实现了给定接口而不实例化它,并且没有反射 API:

// checks if class Bar implements Foo
if (in_array('Foo', class_implements('Bar'))) {
    $foo = new Bar;
} else {
    throw new Exception('Interface not implemented');
}
于 2011-01-27T00:02:10.590 回答
0

未经测试,但理论上这是 API:

<?php
$reflection = new ReflectionClass('DingleBerry');
$reflection->implementsInterface('Requirements');
?>

http://php.net/manual/en/book.reflection.php
http://mark-story.com/posts/view/using-the-php-reflection-api-for-fun-and-profit

于 2011-01-26T23:50:14.993 回答