栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在PHP中检查特定类型的对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在PHP中检查特定类型的对象

您可以使用

instanceof

if ($pdo instanceof PDO) {    // it's PDO}

但是请注意,您不能像否定

!instanceof
,所以您应该这样做:

if (!($pdo instanceof PDO)) {    // it's not PDO}

另外,查看您的问题,您可以使用对象类型提示,它有助于强制执行要求并简化检查逻辑:

function connect(PDO $pdo = null){    if (null !== $pdo) {        // it's PDO since it can only be        // NULL or a PDO object (or a sub-type of PDO)    }}connect(new SomeClass()); // fatal error, if SomeClass doesn't extend PDO

输入的参数可以是必需的或可选的:

// required, only PDO (and sub-types) are validfunction connect(PDO $pdo) { }// optional, only PDO (and sub-types) and // NULL (can be omitted) are validfunction connect(PDO $pdo = null) { }

无类型的参数可通过显式条件实现灵活性:

// accepts any argument, checks for PDO in bodyfunction connect($pdo){    if ($pdo instanceof PDO) {        // ...    }}// accepts any argument, checks for non-PDO in bodyfunction connect($pdo){    if (!($pdo instanceof PDO)) {        // ...    }}// accepts any argument, checks for method existancefunction connect($pdo){    if (method_exists($pdo, 'query')) {        // ...    }}

至于后者( 使用

method_exists
),我的观点有点复杂。来自Ruby的人们会发现
respond_to?
,无论好坏,它都是熟悉的。我将亲自编写一个接口并针对该接口执行普通的类型提示:

interface QueryableInterface{     function query();}class MyPDO extends PDO implements QueryableInterface { }function connect(QueryableInterface $queryable) { }

但是,这并不 总是 可行的。在此示例中,

PDO
对象不是有效的参数,因为基本类型未实现
QueryableInterface

还值得一提的是,在PHP中, 值具有类型 ,而不是变量。这很重要,因为

null
将使
instanceof
检查失败。

$object = new Object();$object = null;if ($object instanceof Object) {    // never run because $object is simply null}

当值变成时,它失去类型

null
,缺少类型。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/594744.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号