doulingna9420 2016-03-29 15:06
浏览 151
已采纳

instanceof Carbon失败了

In my application I use something like the following

if($val instanceof Carbon)
...

unfortunately unless I previously use Carbon in the code (even if just Carbon::now();) it will always return false. Why?

  • 写回答

1条回答 默认 最新

  • dongsong8932 2016-03-30 07:45
    关注

    You are using Laravel's class auto-loader. You've defined this at config/app.php:

    'Carbon' => Carbon\Carbon::class,
    

    ... so when you run this for the first time:

    Carbon::now();
    

    ... PHP needs a Carbon class that is not defined yet so class auto-loading gets triggered and Laravel loads the Carbon\Carbon namespace and defines a Carbon alias. Thus $val instanceof Carbon can return true if the variable has the correct type.

    However, instanceof itself will not trigger class auto-loading. Documentation suggests it did that in the past but it no longer does:

    Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist.

    Demo

    (I admit I still don't have an explanation of how you can make $val be an instance of Carbon if you haven't loaded the class yet.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?