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

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

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器