从函数返回true或int的更好方法


a better way to return true or int from function

我有一个Address_Finder类,方法为get_address( $ordinal, $postcode ),它使用谷歌地图API和数据库的混合来获得完整地址

get_address$ordinal$postcode中查找地址详细信息:lat、lng、street_name等,一旦调用,就会将实例的地址变量设置为结果。

如果成功找到地址,则将内部数据设置为结果并返回true

但是,如果该地址已存在于数据库中,则返回该地址在数据库中的address_id

很明显,函数的返回值要么是true,要么是标准的php整数类型。

我们可以这样做:

$address = new Address_Finder();
$address_id = $address -> get_address( "2", "NG8 5NW" );
if ( $address_id ){
    $address_id = $address -> save(); // saves the address to the database
}

现在,如果get_address返回true,或者如果它返回$address_id 1,则if ( $address_id )将计算为true。

这可以通过以下操作来解决:

if ( $address_id === true ){
    // save returns the address ID of the last inserted address
    $address_id = $address -> save();
}

然而,我想知道是否有更好的方法来做到这一点?

就像。。。我希望在我的博客上发布我的Address_Finder类作为API,这样其他程序员就可以使用它了

因此,通过"更好的方式",我正在思考程序员将如何使用我的API

返回一个数组而不是一个简单的值:

{
 'success':true||false,  //boolean indicating if get_address was successfull
 'id':     int||null     //id returned by get_address when successfull
}