我知道我的问题在某种程度上是错误的,但我仍在努力解决这个问题。
我有一个接口Programmer
:
interface Programmer {
public function writeCode();
}
和几个命名的类:
Students'BjarneProgrammer
(实现Programmer
)Students'CharlieActor
(实现Actor
)
我有这个类名存储在数组$students = array("BjarneProgrammer", "CharlieActor");
中
我想写一个函数,如果它实现Programmer
接口,它将返回类的一个实例。
示例:
getStudentObject($students[0]);
-它应该返回BjarneProgrammer
的一个实例,因为它正在实现Programmer。
getStudentObject($students[1]);
-它应该返回false
,因为Charlie不是程序员。
我尝试使用instanceof
运算符,但主要问题是,如果对象没有实现Programmer,我不想实例化它。
我检查了如何动态加载php代码,并检查类是否实现接口,但并没有合适的答案,因为除非函数返回,否则我不想创建对象。
您可以使用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
作为字符串作为函数的参数传递。此外,您可以使用反射
$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();
}
如果您使用的是现代版本的PHP(5.3.9+),那么最简单(也是最好)的方法是使用带有第三个参数true
:的is_a()
$a = "Stdclass";
var_dump(is_a($a, "stdclass", true));
var_dump(is_a($a, $a, true));
这两种情况都会成真。
使用PHP的函数is_subclass_of():
use App'MyClass;
use App'MyInterface;
if (is_subclass_of(MyClass::class, MyInterface::class)) {
// ...
}