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


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


if ($var instanceof DateTime) {
    // true


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

至於 instanceof 和 is_a 之間的差異



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?


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).


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

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

Twitter picture

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


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

Google+ photo

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

連結到 %s