Mad*_*iha 62 php oop object-type
我有接受一个PDO对象作为参数,以允许用户使用现有的连接,而则该方法以打开一个新的,并保存资源的方法:
public static function databaseConnect($pdo = null) {
Run Code Online (Sandbox Code Playgroud)
我知道is_object()检查参数是否是一个对象,但我想检查是否$pdo是一个PDO对象,而不仅仅是一个对象.
因为用户可以轻易地输入(错误地?)不同类型的对象,mysqli等,并且整个脚本将分开.
简而言之:如何检查特定类型对象的变量?
Dan*_*ugg 86
你可以使用instanceof:
if ($pdo instanceof PDO) {
// it's PDO
}
Run Code Online (Sandbox Code Playgroud)
但要注意,你不能否定!instanceof,所以你要做的是:
if (!($pdo instanceof PDO)) {
// it's not PDO
}
Run Code Online (Sandbox Code Playgroud)
另外,查看您的问题,您可以使用对象类型提示,这有助于强制执行要求,以及简化检查逻辑:
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
Run Code Online (Sandbox Code Playgroud)
输入的参数可以是必需的或可选的:
// required, only PDO (and sub-types) are valid
function connect(PDO $pdo) { }
// optional, only PDO (and sub-types) and
// NULL (can be omitted) are valid
function connect(PDO $pdo = null) { }
Run Code Online (Sandbox Code Playgroud)
无类型参数允许通过显式条件实现灵活性:
// accepts any argument, checks for PDO in body
function connect($pdo)
{
if ($pdo instanceof PDO) {
// ...
}
}
// accepts any argument, checks for non-PDO in body
function connect($pdo)
{
if (!($pdo instanceof PDO)) {
// ...
}
}
// accepts any argument, checks for method existance
function connect($pdo)
{
if (method_exists($pdo, 'query')) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
至于后者(使用method_exists),我认为我有点混乱.来自Ruby的人会发现respond_to?,无论好坏都很熟悉.我个人会编写一个接口并执行一个正常的类型提示:
interface QueryableInterface
{
function query();
}
class MyPDO extends PDO implements QueryableInterface { }
function connect(QueryableInterface $queryable) { }
Run Code Online (Sandbox Code Playgroud)
但是,这并不总是可行的; 在此示例中,PDO对象不是有效参数,因为基本类型未实现QueryableInterface.
值得一提的是,PHP 中的值有类型,而不是变量.这很重要,因为检查null失败instanceof.
$object = new Object();
$object = null;
if ($object instanceof Object) {
// never run because $object is simply null
}
Run Code Online (Sandbox Code Playgroud)
当它变为null缺乏类型时,该值会丢失它的类型.
Oli*_* A. 11
使用
bool is_a ( object $object , string $class_name )
Run Code Online (Sandbox Code Playgroud)
这也适用于子类.
编辑:或者您可以使用类型提示:
public static function databaseConnect(PDO $pdo = null) {...
Run Code Online (Sandbox Code Playgroud)