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