如何在 PHP 中检查特定类型的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8091143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Check for a Specific Type of Object in PHP
提问by Madara's Ghost
I have a method which accepts a PDO object as an argument, to allow the user to use an existing connection rather then the method to open a new one, and save resources:
我有一个接受 PDO 对象作为参数的方法,以允许用户使用现有连接而不是打开新连接的方法,并节省资源:
public static function databaseConnect($pdo = null) {
I am aware of is_object()
to check if the argument is an object, but I want to check if $pdo
is a PDO object, and not just an object.
我知道is_object()
要检查参数是否是对象,但我想检查是否$pdo
是 PDO 对象,而不仅仅是对象。
Because the user can easily enter (by mistake?) a different kind of object, a mysqli or such, and the entire script will break apart.
因为用户可以很容易地(错误地?)输入不同类型的对象,一个 mysqli 之类的,并且整个脚本将分崩离析。
In short: How can I check a variable for a specific type of object?
简而言之:如何检查特定类型对象的变量?
回答by Dan Lugg
You can use instanceof
:
您可以使用instanceof
:
if ($pdo instanceof PDO) {
// it's PDO
}
Be aware though, you can't negate like !instanceof
, so you'd instead do:
但是请注意,您不能否定 like !instanceof
,因此您应该这样做:
if (!($pdo instanceof PDO)) {
// it's not PDO
}
Also, looking over your question, you can use object type-hinting, which helps enforce requirements, as well as simplify your check logic:
此外,查看您的问题,您可以使用对象类型提示,这有助于强制执行要求,并简化您的检查逻辑:
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
Typed arguments can be required or optional:
类型参数可以是必需的或可选的:
// 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) { }
Untyped arguments allow for flexibility through explicit conditions:
无类型参数允许通过显式条件实现灵活性:
// 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')) {
// ...
}
}
As for the latter (using method_exists
), I'm a bit mixed in my opinion. People coming from Ruby would find it familiar to respond_to?
, for better or for worse. I'd personally write an interface and perform a normal type-hint against that:
至于后者(usingmethod_exists
),我的看法有点复杂。来自 Ruby 的人会发现它很熟悉respond_to?
,无论好坏。我会亲自编写一个接口并对其执行正常的类型提示:
interface QueryableInterface
{
function query();
}
class MyPDO extends PDO implements QueryableInterface { }
function connect(QueryableInterface $queryable) { }
However, that's not alwaysfeasible; in this example, PDO
objects are not valid parameters as the base type doesn't implement QueryableInterface
.
然而,这并不总是可行的。在此示例中,PDO
对象不是有效参数,因为基本类型未实现QueryableInterface
。
It's also worth mentioning that values have types, not variables, in PHP. This is important because null
will fail an instanceof
check.
还值得一提的是,值在 PHP 中具有类型,而不是变量。这很重要,因为null
将无法通过instanceof
检查。
$object = new Object();
$object = null;
if ($object instanceof Object) {
// never run because $object is simply null
}
The value loses it's type when it becomes null
, a lack of type.
当值变成 时,它就失去了它的类型null
,缺少类型。
回答by Oliver A.
use
用
bool is_a ( object $object , string $class_name )
This will work for child classes too.
这也适用于儿童班。
EDIT: Or you could use type hinting:
编辑:或者您可以使用类型提示:
public static function databaseConnect(PDO $pdo = null) {...
回答by Weston C
As pointed out in other answers, instanceof
, get_class
, and is_a
are probably what you're looking for.
正如其他答案中所指出的,instanceof
, get_class
, 和is_a
可能是您正在寻找的。
However, rather than coding in a lot of guards that test for type, some developers find it more productive (and easier to read) to just let the runtime handle the enforcement, particularly when you're talking about calls other programmers will be making (when a programmer makes a mistake, app-breaking loud complaints are arguably a good thing).
然而,与其在大量测试类型的守卫中编码,一些开发人员发现让运行时处理强制执行更有效率(也更容易阅读),特别是当你谈论其他程序员将进行的调用时(当程序员犯错误时,破坏应用程序的大声抱怨可以说是一件好事)。
If you really need to not have the script fall apart when a programmer uses your method incorrectly, wrap the relevant section of code (in this case, probably the inside of databaseConnect) in a try block, maybe use set_error_handlerto throw exceptions on script errors, and then set up one or more catch blocks which indicated what to do when an exception condition happens.
如果你真的不想在程序员错误地使用你的方法时让脚本崩溃,请将相关的代码部分(在这种情况下,可能是 databaseConnect 的内部)包装在一个try 块中,也许使用set_error_handler在脚本错误时抛出异常,然后设置一个或多个 catch 块,指示发生异常情况时要执行的操作。
回答by Sarfraz
I think you can use instanceof
something like:
我认为你可以使用instanceof
类似的东西:
if ($pdo instanceof YOUR_PDO_OBJECT_INSTANCE) {
// it is...
}