【发布时间】:2021-02-03 18:02:46
【问题描述】:
我有大约这个 PHP 代码:
class DatabaseItem
{
private const CLASS_NAMES = null;
public function doStuff()
{
if ($this::CLASS_NAMES['property'] instanceof self)
{
//Construct the Profile Picture object and save it into the property of the $user instance
}
}
}
class ProfilePicture extends DatabaseItem { /* Unimportant stuff */ }
class User extends DatabaseItem
{
protected const CLASS_NAMES = array('property' => ProfilePicture);
protected $profilePic;
}
$user = new User();
$user->doStuff();
我知道这段代码看起来很不合逻辑,但我不得不对其进行大量简化。无论如何,问题是,条件($this::CLASS_NAMES['property'] instanceof self) 总是评估为假。有没有办法检查一个类(不是它的实例)是否扩展或实现了不同的类/接口?
【问题讨论】:
-
instanceof的第二个操作数应该是类,而不是类实例。 -
我认为你只是把它倒过来了:
$this instanceof $this::CLASS_NAMES['property'] -
doStuff()需要$user参数,但您使用空参数列表调用它。 -
感谢您的回复,但问题是,我没有任何类的实例。我只知道他们的名字。结果,我不能使用 $this。在示例中,我试图找出
ProfilePicture类是否扩展了DatabaseItem类,它确实如此。关于缺少的$user参数,这只是一个错字,已经修复了。 -
array('property' => ProfilePicture)ProfilePicture 的常量。你的意思是ProfilePicture::class?
标签: php class oop inheritance class-hierarchy