در حال بارگذاری ...

Setting Up PSR-4 Autoloading0:00

When importing with the use keyword, we can now group declarations. Not a huge feature, but still useful in some cases. Let me show you. Let's very quickly create a composer.json file. And I'm just going to say that I want to use PSR-4 to autoload, using an app namespace, anything in this current directory. Okay, so I will do a quick composer install. That'll pull in my autoloader and things like that. Great. So let's create just some dummy classes here.

Creating Dummy Classes0:27

Great. So let's create just some dummy classes here. namespace app class Person. And how about one more for the obligatory Animal? How about that? namespace app and class Animal. Okay, so we have two files that we want to autoload. So let's pull in our autoloader. And now I can say use app\Person. And if we were to var_dump new Person, naturally from my VM,

Importing Single Classes0:50

And now I can say use App\Person. And if we were to var_dump new Person, naturally from my VM, if we were to run this, yeah, we get our Person object, right? But if we also wanted to new up an Animal, well, before PHP 7, you would have to do something along these lines. Even though it's in the same namespace, you don't have the ability to import everything, unfortunately. That's a shame. So yeah, you'd have to do this. Okay, but now in PHP 7,

Grouping Use Declarations1:16

So yeah, you'd have to do this. Okay, but now in php 7, well, it's a little awkward, but it gets the job done. We can wrap it within a brace here. So within the app namespace, I want to use Person as well as Animal. And now I can remove that. All right, so if we were to var_dump new instances of both of these, it will still work. But of course, before php 7, that would trigger an error. Now, in terms of formatting, let me clear my sniffer marks.

Formatting Grouped Imports1:38

But of course, before PHP 7, that would trigger an error. Now, in terms of formatting, let me clear my sniffer marks. Yeah, you can do basically whatever you want. So for example, if you like that syntax, you can do it. If you want it all on its own line, that would be fine as well. And remember, within here, you could go further. So if you want to use app foo bar and then some baz class, well, then right here, you're already within app, so you could say foo bar baz. And that would achieve the exact same thing.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟