PHP 判斷物件是否是哪個類別型態?

From: http://stackoverflow.com/questions/9568793/php-check-for-instance-of-datetime

使用 instanceof 或是 is_a 都可以判斷變數是否是哪個類型。

instancof

if ($var instanceof DateTime) {
    // true
}

is_a

if (is_a($var, ‘DateTime’) {
    // true
}

至於 instanceof 和 is_a 之間的差異

From: http://stackoverflow.com/questions/3017684/what-is-the-difference-between-is-a-and-instanceof

Q:

I am aware that instanceof is an operator and that is_a is a method.

Is the method slower in performance? What would you prefer to use?

A:

Actually, is_a is a function, whereas instanceof is a language construct. is_a will be significantly slower (since it has all the overhead of executing a function call), but the overall execution time is minimal in either method.

It’s no longer deprecated as of 5.3, so there’s no worry there.

There is one difference however. 

is_a being a function takes an object as parameter 1, and a string as parameter 2. 

instanceof can take either a string as parameter, object, or an identifier (class name written without quotes).

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s