2013-11-24 26 views
8

我明白我的问题有点不对,但我仍然试图解决这个问题。PHP - 检查类名是否存储在一个字符串正在实现一个接口

我有一个接口Programmer

interface Programmer { 
    public function writeCode(); 
} 

和一对夫妇命名空间类:

  • Students\BjarneProgrammer(实现Programmer
  • Students\CharlieActor(实现Actor

我存储在阵列$students = array("BjarneProgrammer", "CharlieActor");

我想编写一个函数这个类的名字,如果它实现Programmer界面,将返回类的一个实例。

例子:

getStudentObject($students[0]); - 因为它是实现程序员应该返回BjarneProgrammer一个实例。

getStudentObject($students[1]); - 它应该返回false,因为查理不是程序员。

我试过使用instanceof运算符,但主要问题是我不想想实例化一个对象,如果它没有实现程序员。

我检查了How to load php code dynamically and check if classes implement interface,但没有合适的答案,因为我不想创建对象,除非它是由函数返回的。

+0

@how:OP说他们不想实例化类。 –

回答

12

您可以使用class_implements(需要PHP 5.1.0

interface MyInterface { } 
class MyClass implements MyInterface { } 

$interfaces = class_implements('MyClass'); 
if($interfaces && in_array('MyInterface', $interfaces)) { 
    // Class MyClass implements interface MyInterface 
} 

您可以通过class name作为一个字符串作为函数的参数。此外,您还可以使用Reflection

$class = new ReflectionClass('MyClass'); 
if ($class->implementsInterface('MyInterface')) { 
    // Class MyClass implements interface MyInterface 
} 

更新:(你可以尝试这样的事情)

interface Programmer { 
    public function writeCode(); 
} 

interface Actor { 
    // ... 
} 

class BjarneProgrammer implements Programmer { 
    public function writeCode() 
    { 
     echo 'Implemented writeCode method from Programmer Interface!'; 
    } 
} 

功能来检查并返回instanse/false

function getStudentObject($cls) 
{ 
    $class = new ReflectionClass($cls); 
    if ($class->implementsInterface('Programmer')) { 
     return new $cls; 
    } 
    return false; 
} 

获取一个实例或假

$students = array("BjarneProgrammer", "CharlieActor"); 
$c = getStudentObject($students[0]); 
if($c) { 
    $c->writeCode(); 
} 
+0

谢谢,你的回答帮了我。我只用了ReflectionClass - http://codepad.org/EvZRbaWZ – Stichoza

+0

@Stichoza,谢谢,欢迎!我也更新了答案。 –

+0

我使用的方法ReflectionClass'返回$ class-> newInstance();'而不是'返回新$ cls;''。再次感谢:> – Stichoza

10

如果您使用PHP的现代版本(5.3.9+),那么最简单的(和最好)的方法是使用is_a()第三个参数true

$a = "Stdclass"; 

var_dump(is_a($a, "stdclass", true)); 
var_dump(is_a($a, $a, true)); 

这两项的将返回true。

+0

PHP文档是一种误导(如果你不在乎每一句话:)) - 它说is_a的第一个参数是一个对象。但如果你阅读 - 你会发现它实际上可以是一个字符串...... –

相关问题