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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)