强制动态加载的类扩展或实现接口
有人知道在 PHP 中是否可以强制一个类扩展或实现一个接口,而无需子类声明它?
示例:
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;
显然这不起作用,但我需要一种加载类的方法,这些类没有预先确定的接口要求知识,但被迫遵守它们。
我的总体目标是检查该类是否在加载之前实现了要求并且调用了它的构造函数。
所以我不能使用这个:
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.
}
因为在我检查 DingleBerry 的构造函数是否实现要求之前,它会被调用。挖?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果不使用第三方扩展(例如:runkit),则无法修改已声明的类或接口定义。
Runkit 有一个 runkit_class_adopt 函数可以满足该需求。不幸的是我无法测试它,因为 PECL 版本无法在我的机器上编译。
对于问题的第一部分,您可以检查一个类是否实现了给定的接口而不实例化它,并且没有反射 API:
You cannot modify an already declared class or interface definition without using a third-party extension (e.g.: runkit).
Runkit has a runkit_class_adopt function that may fulfil that need. Unfortunately I can't test it because the PECL version won't compile on my machine.
For the first part of your question, you can check if a class implements a given interface without instantiating it, and without the Reflection API:
未经测试,但理论上这是 API:
http://php.net/manual/en/book .reflection.php
http://mark-story .com/posts/view/using-the-php-reflection-api-for-fun-and-profit
Untested but theoretically this is the API:
http://php.net/manual/en/book.reflection.php
http://mark-story.com/posts/view/using-the-php-reflection-api-for-fun-and-profit