PHP Traits - How They Work & Drawbacks - Full PHP 8 Tutorial

  Рет қаралды 31,389

Program With Gio

Program With Gio

Күн бұрын

In this video, you will learn all you need to know about traits in PHP with examples & in-depth explanations. You'll learn what problems traits solve as well as the problems it can introduce.
SOME OF THE WAYS YOU CAN SUPPORT THE CHANNEL
👍 Smash the like button
🤝 Subscribe to the channel & turn the notifications on
💬 Post comments, any feedback is greatly appreciated
⭐ Become a Patreon: / programwithgio
THANK YOU!
LESSON 2.14
Course Outline - github.com/ggelashvili/learnp...
Course Playlist - • Learn PHP The Right Wa...
RESOURCES
www.php.net/manual/en/languag...
CHAPTERS
00:00 - Intro
00:27 - Multiple inheritance problem
02:02 - Overview of coffee maker example in code
03:08 - Using interfaces instead of multiple inheritance
05:43 - Creating & using traits
08:22 - How do traits work?
08:39 - Method precedence
11:02 - Conflict resolution ("insteadof" & "as" operators)
13:38 - Changing visibility of trait methods
16:02 - Composing traits from other traits
16:46 - Properties within traits
20:40 - Abstract methods in traits
23:19 - Static properties & methods in traits
25:38 - Magic _CLASS_ constant in traits
26:13 - Personal opinion & downsides of traits
28:46 - Example comparing inheritance & traits

Пікірлер: 191
@iraklyoda4213
@iraklyoda4213 Жыл бұрын
Hello Gio. Just wanted you to know that with help of your PHP course I just landed my first full-time job as a web-developer. Thank you for your work! All the theoretical knowledge really helped me to perform at interview
@ProgramWithGio
@ProgramWithGio Жыл бұрын
That is amazing, congratulations & thank you for sharing this info, you just made my day 🙌
@JohnnyBigodes
@JohnnyBigodes 3 жыл бұрын
This is real hard stuff to digest, but you have perfectly explained how it works and how it should be used. Thanks
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Thank you 🙏
@mwaas
@mwaas Жыл бұрын
this course should be main reference to learn php. all things is perfect and it is really the right( and the perfect )way to learn php
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Appreciate the kind words, thank you 🙏
@federicobau8651
@federicobau8651 2 жыл бұрын
Best php traits and oop tutorial and best php course, better than paid bootcamps
@free2idol1
@free2idol1 10 ай бұрын
Thank Gio! The more I watch your series, the deeper I understand php advanced concepts. I hope you would enjoy my little support here.
@ProgramWithGio
@ProgramWithGio 10 ай бұрын
That's awesome, happy to hear it. Thank you for your support 🙏💙
@DanielAbernathy
@DanielAbernathy 3 жыл бұрын
Very comprehensive look at traits! I learned a couple things I didn't know.
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Glad it was useful, thank you Daniel
@WhiteSiroi
@WhiteSiroi Жыл бұрын
Thank you so much, I love that you give your thoughts on best practices and share your experience, like use traits for code reusability so we can avoid duplications and wrong use of inheritance.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You're welcome, happy to hear that 💙
@lotuslando1994
@lotuslando1994 5 ай бұрын
I'm finding your use of real world examples, like coffeemakers, really, really helpful in understanding the concept of traits. I don't have to spend a lot of time trying conceptualize how this works. I know how coffeemakers work. I know what different types of coffee are. This made this lesson very easy to absorb and understand. Thanks again for coming up with such creative, and RELATABLE, ways to impart this information. 🙂
@ProgramWithGio
@ProgramWithGio 5 ай бұрын
Awesome, happy to hear 💙
@Vlodko_S
@Vlodko_S 2 жыл бұрын
Thank you! That's the best explanation of traits I've ever seen. Now all is pretty clear
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Glad to hear, thank you 💙
@pat1938
@pat1938 2 жыл бұрын
Hey, thanks for the video, it really made me understand why I should use traits (very often just by reading documentation I get the idea of what something is but I never end up actually using the feature).
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Hello 👋. Really glad to hear that 🙌
@devangbaroliya2899
@devangbaroliya2899 3 жыл бұрын
Love the way u explain. Plz, make series on the projects after this.
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Thank you. Will do 👍
@karamm3353
@karamm3353 2 жыл бұрын
Another great tutorial. Thank you for sharing all these concepts
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
You're welcome & thank you
@Armando-px8hi
@Armando-px8hi Жыл бұрын
I guess it was the last common lesson related to OOP's common features. Another great work with the memes as well. Highly respected GIO!
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you
@aristuzabaru
@aristuzabaru Жыл бұрын
🤯🤯🤯 I guess I'll have to watch it a few more times. Great content and great instructor as always!
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you. Take your time 🙌
@mezdelex
@mezdelex 3 жыл бұрын
Great in-depth explanation. So we could say that traits share functionality logic with mixins as a way to avoid repeating code instead of using it in a more complex and not recommended way.
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Yup pretty much. Thank you
@free2idol1
@free2idol1 Жыл бұрын
12:38: `LatteTrait::makeLatte insteadof CappuchinoTrait` => this is new to me. Thanks Gio very much for your unique advanced tutorial.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You're welcome, glad you like it
@udalathudar
@udalathudar 7 ай бұрын
Thank you for this amazing PHP series, finally learned about Trait.
@ProgramWithGio
@ProgramWithGio 7 ай бұрын
That's awesome, great to hear
@user-zh2oz9fe4m
@user-zh2oz9fe4m 11 ай бұрын
Traits is a quite powerful feature. Thanks for this video!
@ProgramWithGio
@ProgramWithGio 11 ай бұрын
It really is
@benfaerber4956
@benfaerber4956 2 жыл бұрын
Great tutorial! I'm a beginner Laravel dev and I'm trying to understand how to best use the framework and PHP in general.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Thank you. That's awesome, Laravel is great and I use it everyday.
@oghenevwefepeace2501
@oghenevwefepeace2501 2 жыл бұрын
Finally, understand the meaning of traits. Thank you
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Glad to hear that, thank you 🙌
@ryancurrington4398
@ryancurrington4398 Жыл бұрын
Great job explaining, thanks for sharing your knowledge.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Glad it was helpful, thank you
@Zubbee
@Zubbee 2 жыл бұрын
I like Traits. This lesson is like one of the longests so far and I thought it would be hard to understand since it's long but it wasn't. I followed. I totally see what you are saying about it being better to use traits for code reuse and not for declaring properties or as contracts. I'm learning alot. Thanks Gio. PS - Can traits be leveraged in procedural php structures?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
That's awesome, thank you 🙌. Traits are for OOP, you need classes to use traits
@rangingaway92
@rangingaway92 6 ай бұрын
Best course for free. Enjoy the coffee and keep going.☕
@ProgramWithGio
@ProgramWithGio 6 ай бұрын
Thank you for your support 🙏
@fabiosimedo
@fabiosimedo 2 жыл бұрын
I found it extrmely informative Thank you!
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Glad it was helpful
@massimoramaj3233
@massimoramaj3233 11 ай бұрын
Great explanation as always!
@ProgramWithGio
@ProgramWithGio 11 ай бұрын
Glad you liked it, thank you
@ItsDigiUtime
@ItsDigiUtime Жыл бұрын
Really appreciate you mentioning PSR-12 standards even with the small things like separating use statements on their own line. In my 2 and a half years of programming I have only met one developer who knew about this or said it out loud (I found out about it from him). Can't blame others because even in Laravel for example with auto generated code (when initialising a new project), it is not taken into account (for example the generated User class at the start). Just need to raise awareness more I guess to reach people who care but some people really do not care about PSR-12 and ignore it even when told about it.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
I agree, but in my opinion as long as you follow some sort of standard & convention and stay consistent its still better even if its not PSR-12. Laravel has its own conventions and they are somewhat consistent, so when I use Laravel I try to be consistent & follow the same conventions as well
@SaiyanJin85
@SaiyanJin85 10 ай бұрын
Great video as always, I think if we ended up having the same method signature in multiple traits used in a class then it’s code smell on our design in general, it’s nice though that php provides a way to chose which one to execute
@SaiyanJin85
@SaiyanJin85 10 ай бұрын
Also changing the visibility of a method in a trait should not been done especially by junior devs, it’s going to be a really bad habit down the road
@ProgramWithGio
@ProgramWithGio 10 ай бұрын
Yup for sure
@rashmimore5844
@rashmimore5844 2 ай бұрын
Thank you for the great video !
@ProgramWithGio
@ProgramWithGio 26 күн бұрын
Glad you liked it!
@emekatimothyiloba699
@emekatimothyiloba699 Жыл бұрын
I used this last use case of traits you explained in a project i just completed
@ProgramWithGio
@ProgramWithGio Жыл бұрын
That's awesome, good job
@godmansarah
@godmansarah 2 жыл бұрын
Thanks for this video! I think I do grasp the concepts better when there are examples like CoffeeMaker and Mail, rather than just Class A and Class B, foo and bar, and var_dumps :) So it seems that if you use a trait inside another trait and have a class that call both the "parent" trait and "child" trait, that is fine with the "duplication" of code, as PHP knows that is not a conflict? As in 16:40, CappuccinoTrait uses LatteTrait, and AllInOneCoffeeMaker uses both CappuchinoTrait and LatteTrait, and it seems to be fine.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Yes, when using traits within traits it won't conflict unless you define a method with the same name.
@udayan285
@udayan285 8 ай бұрын
Thank you Gio.
@ProgramWithGio
@ProgramWithGio 7 ай бұрын
You're welcome
@ilya_123__
@ilya_123__ 8 ай бұрын
Thank you for you great job!
@ProgramWithGio
@ProgramWithGio 8 ай бұрын
You're very welcome 💙
@SoleilMagica
@SoleilMagica 2 жыл бұрын
This is good, thanks!
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Glad you like it, thank you
@dawid_dahl
@dawid_dahl 2 жыл бұрын
Excellent video, thanks! Do you have any videos on how to unit test things like traits?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Thank you. Beginning of section 3 is about testing & PHPUnit. Though I don't have anything on testing traits specifically. Might make a separate video on that.
@siddheshb.kukade4685
@siddheshb.kukade4685 3 жыл бұрын
hey, till 9:00 you were using traits for latteMaker and cappuccino classes but as we have discu Cssed earlier the problem was in the coffeemaker class and I think you should create a trait of cofffeMaker class which was actually causing ambiguity instead of the lattemaker and cappuccino classes. let me know if I'm wrong ... btw Great Video Sir 🔥 Edit : After rewatching I think that my solution is just another way yours is also correct after all, All the trait is doing is copying and pasting the code. actually, I was confused with the same C++ concept of *abstract methods* 👍‍‍
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Yup, traits are mainly to reduce code duplication & reuse the code instead
@hardikjogadiya3356
@hardikjogadiya3356 Жыл бұрын
Wow, traits can be so awesome.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
For sure
@syedanwar1872
@syedanwar1872 Жыл бұрын
your content worth trillion :)
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you 🙏
@webdeveloper1933
@webdeveloper1933 3 жыл бұрын
Thanks for this awesome series, are you going to have series about Design Patterns? that would be great,, thanks in advance !!!
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
You're welcome & thank you. Yes I'm thinking of making separate lessons about design patterns, though some design patterns will be part of this course as well in third section.
@noneavailable6742
@noneavailable6742 2 жыл бұрын
Hello. Before i ask my question i just wanna thank you for this series, it's definitely one of, if not the most comprehnsive and straight forward course i've watched. My question is regarding the setMilkType method in 22:30. Why do we "return $this"? aren't setters supposed to change the state of the object and not return anything? I've tried doing it without returning anything and it works but i'm not sure if i'm missing something here.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Hello. Thank you 🙌. Returning the current object allows method chaining
@noneavailable6742
@noneavailable6742 2 жыл бұрын
@@ProgramWithGio Ahh, got it now. Thank you :)
@hansschuijff
@hansschuijff Жыл бұрын
Great course, Gio. I appreciate your effort here and the many examples you offer to make each subject clear. In the last example of this lesson you propose making an Email class and then extending the Invoice and Customer class to it. I agree that that would not be logical and a trait would be better in that case. But is extending the best probable way to use such a class? It seems that perhaps making an Email class would not be so bad if you just instantiate it and then use a send method on it. It would add a dependency, so probably that would be a subject here, but is there something wrong with just coding it something like this? $email = new Email( $from, $to, $subject, $content ); $email->send(); Anyway, thank you very much for such an extended and clear php course.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you & great question. That is totally fine & actually the better way, it was just an example in this lesson to see how traits could be used but in general in such cases I go for dependency injection & creating objects on its own instead of having hard dependencies. Whichever class needs email object can just accept it in the constructor or within the method.
@frednights7626
@frednights7626 Жыл бұрын
Thanks!
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you for your support 💙💙
@invgreat5608
@invgreat5608 Жыл бұрын
Thank you!!!!
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You're welcome!
@eivis75
@eivis75 Жыл бұрын
Thank you, as a fresh beginner I like this course so far. However, I keep having one thought in my head, how and where will I use all of this, I think I would have problems implementing simple concepts. It is a bit hard to connect all learnt stuff right now... But I guess everything will get clearer with practice, at least I will learn these concepts and it will be much easier, when I will revisit in the future.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You'll just have to build projects & apply them there. Practice is what will make it stick. We are building a project at the end of this series as well.
@memack101
@memack101 Жыл бұрын
Thank you.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You're welcome 💙
@emekatimothyiloba699
@emekatimothyiloba699 Жыл бұрын
God bless you Gio
@ProgramWithGio
@ProgramWithGio Жыл бұрын
You too 🙌
@fury_uri
@fury_uri 2 жыл бұрын
Great explanation and visuals/code examples. Almost didn't watch it due to the instructor's monotonous vocal quality, but I'm glad I did. Maybe try speaking more naturally instead of reading (?). At any rate, thanks for this helpful video!
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Thank you. I'm usually not reading while coding, it's just the way I sound. I can't fake the emotions 😁, I know I may sound boring, I'll try to improve that
@fury_uri
@fury_uri 2 жыл бұрын
@@ProgramWithGio 😅 - ah. Well, nice job in not reading a script. I plan to check out the rest of your videos and courses. Keep up the great work!
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
@@fury_uri thank you 💙
@celesteomalowete7010
@celesteomalowete7010 6 ай бұрын
Thanks
@ProgramWithGio
@ProgramWithGio 6 ай бұрын
Thank you 🙏
@abdallakaram5376
@abdallakaram5376 3 жыл бұрын
Very excellent explanation, but I hope it will be a little slow. Thank you very much for this valuable information
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Thank you. Sorry if I went a bit too fast, I try to slow down as much as I can. KZfaq also has the option to adjust the speed if needed.
@abdallakaram5376
@abdallakaram5376 3 жыл бұрын
@@ProgramWithGio I am very grateful to you that I will use this property
@thrldr3106
@thrldr3106 2 жыл бұрын
Awesome videos, man! Keep up the good work. So traits are something like composition but with less code, meaning that you don't have to write additional methods to call them from your class, right? But doesn't it go against the dependency injection principle since you can't pass them via the constructor or methods? Using traits you basically enforce unnecessary dependencies as far as I can tell. Doesn't it make traits intrinsically inferior to composition while in a nutshell they are designed to solve the same problem?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Thank you. Traits are not same as composition because code from traits is simply pasted into the class that uses it, so trait code becomes part of the class. This introduces possibilities of conflicts & so on. Composition on the other hand is when you inject dependencies through constructor (There is a lesson about composition coming soon, so it might help understand the difference).
@thrldr3106
@thrldr3106 2 жыл бұрын
​@@ProgramWithGio thank you. Well I mean that traits just look like a generally bad option as far as the OOP is concerned. It couples your classes by binding them with a trait, so if one class needs to change a method of the trait, it either needs to override it, or the other class will have to be changed to stay in touch
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Yes and no, depends how you use traits. Note that traits are not objects like classes, they just become part of a class. The same can be said about inheritance & it is true in many cases but we still use inheritance, its part of the OOP. It depends on how you use it, overusing/misusing traits is just as bad as inheritance & anything else
@free2idol1
@free2idol1 Жыл бұрын
​@@thrldr3106 Hi, I think if you need to rewrite a method then you will end up rewriting it anyway, regardless of using Trait. Like this above coffee maker example. If you don't want the makeLatte() provided by MakeLatterTrait, then you have to write your own method irrespective of using MakeLatterTrait or not.
@siddheshb.kukade4685
@siddheshb.kukade4685 3 жыл бұрын
waiting for next videos
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
👍
@jgabrielmaster
@jgabrielmaster 2 жыл бұрын
Hey there! A quick question that came to mind at the very end of the video: you used a trait Mail to avoid code duplication when that functionality was needed by the Customer and Invoice classes. The question is - would there be a problem in simply importing a Mail class to use it? Thanks in advance.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Nope no problem at all, in fact composition is better in many scenarios in my opinion
@psriniv1
@psriniv1 2 жыл бұрын
@@ProgramWithGio I was going to mention this too, but it was cool to see that you COULD do this with traits. Just makes more sense to me to have $this->emailHandler->send($message) or whatever
@YaidierPerez
@YaidierPerez 29 күн бұрын
Hey there :) First of all thank you for such great content. As your last example (using the Trait Mail)... would it not be better to use a class Mail with an static method sendEmail instead? Thank you :)
@ProgramWithGio
@ProgramWithGio 26 күн бұрын
I avoid use of statics as much as possible. A better way would've been to use dependency injection but this was a lesson about Traits so I showed it as an example
@YaidierPerez
@YaidierPerez 26 күн бұрын
@@ProgramWithGio Thank you very much for your response :)
@aleksandrkanygin2672
@aleksandrkanygin2672 2 жыл бұрын
Hi, thank you for the turorial, btw in the last example (where you show how to use traits for sharing functionality between non-related classes) can we also create a class called something like EmailHandler with sendMail method, and than create an instance of EmailHandler in both classes as property (in Customer and Invoice classes) and when we need to send email functionality call $this->emailHandler->sendEmail(). Would that be a correct solution? Thank you for your time.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Hello. Absolutely, that would be another approach & also the ideal way in my opinion in many cases. Dependency Injection is the right way 👍
@aleksandrkanygin2672
@aleksandrkanygin2672 2 жыл бұрын
@@ProgramWithGio thank you, so that's how it called, I've seen someone do this in similar case and it looked like a correct way. And I see you have a tutorial on that topic, great!
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
@@aleksandrkanygin2672 yup, more fun topics on the way 🙂
@dhiaben20
@dhiaben20 2 жыл бұрын
actually final keyword works in traits, i tried this example and it worked. trait Foo { final public function foo() { echo 'Foo'; } } class ParentClass { use Foo; } class ChildClass extends ParentClass { public function foo() { echo 'Error Can\'t Override Final Method'; } } but if i do the same like you did in 27:51, using Foo trait in ParentClass and immediately override the method in the same class, the error will not be thrown: class ParentClass { use Foo; public function foo() { // i think doing so will just ignore foo method in trait echo 'this will not throw an error'; } }
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Yea that is what I said I think. When you use final keyword in a regular class you cant override that method in a child class but if you use final keyword on a method inside a trait, you can still redefine that method in a class that uses that trait. You can watch 26:44 - 28:00, I show in there that redefining a final method works & does not throw error.
@julienSibille
@julienSibille 2 жыл бұрын
@@ProgramWithGio In that case, using the trait with final keyword in the base class makes it really final for child classes isn't it ?
@godmansarah
@godmansarah 2 жыл бұрын
@@julienSibille Ah I see. This makes sense as using the trait "copies" the code into the class. From then on it is "final" for any classes that extend it.
@rajabhishek5551
@rajabhishek5551 3 жыл бұрын
Please make a video on appointment system
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
The project we'll be working on in this course is not appointment system but it will be fun :)
@kekw5738
@kekw5738 6 ай бұрын
Can we use composition in the last part of video? Customer and Invoice can have relationship "has a" with Mail and it allows us to use sendEmail() method without traits, what problem could be with this?
@ProgramWithGio
@ProgramWithGio 5 ай бұрын
Yes definitely, composition would be better for sure. This was just an example of Traits
@andrepedrosa1525
@andrepedrosa1525 2 жыл бұрын
Hi, in the final example of this video, why not create a class Email, than inside Invoice and Customer create an instance of Email and use method sendEmail? Thank you.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Hello. Yes composition is almost always better, this was just an example of Traits. We cover composition later in the course.
@Omeostatica
@Omeostatica 10 ай бұрын
A question: is it better to use the template method pattern in place of traits?
@ProgramWithGio
@ProgramWithGio 10 ай бұрын
Not really, is not the same. Template pattern if I remember it correctly uses inheritance while traits are used for code reuse. Inheritance shouldn't be used for that in my opinion
@julienSibille
@julienSibille 2 жыл бұрын
Thanks ! Could you tell me when to use trait and when to create a service ? Image you have to register users in multiple places of the application, you create a trait or a service ?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
You would create a trait when you want to reuse code in multiple parts of the application. In your example it depends, why would you need to have a code to register users in multiple places. You could just create a service & use that service everywhere where you need to register the user, I don't think trait would be a good option here.
@julienSibille
@julienSibille 2 жыл бұрын
@@ProgramWithGio Thanks for reply ! To be more explicit: There are parts of the code where i register on the fly a user as a Manager when an EventAnimatorAccount is created. I guess i can still use the service you've mentionned to do it ?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
@@julienSibille service sounds about right or even Model/Repository depending on your project structure
@julienSibille
@julienSibille 2 жыл бұрын
@@ProgramWithGio Thank you so much for you hard work, and then taking time for reply !
@naumanbashir6385
@naumanbashir6385 2 жыл бұрын
Fuck! This is insanely informative.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
😁. Glad to hear that
@free2idol1
@free2idol1 Жыл бұрын
Hi Gio, Before asking my question, I'd like to thank you for creating awesome content. It is hard to find a better tutorial explaining this concept than your video. 18:42: Instead of creating a setter, can I make something like this? `echo static::class . ' is making Latte with ' . $this->milkType ?: "whole-milk";` Is there any bad implication it may cause? Thank you.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Hey, thank you. There is no setter at that timestamp so not sure what you mean, do you mean the getter getMilkType? In general yes you can do that but it is trying to access a magical property that may or may not exist. In some cases that is ok but it is better to have it be returned from a method or at least have a property_exists check
@free2idol1
@free2idol1 Жыл бұрын
@@ProgramWithGio Thank you for your reply. But I could not get what the real benefit of `$this->getMilkType()` over the shorthand method of directly accessing the property ($this->milkType ?: "whole-milk";) is. I understand in the above mini example, the shorthand approach works fine but how about in more complex scenario, why is it not a good idea to directly accessing the property?
@ProgramWithGio
@ProgramWithGio Жыл бұрын
With shorthand approach you are accessing a magical property, it will work yes but its just a preference/code smell type of thing. A method is a bit better because you can define the method within the trait. Can make it abstract and have classes that use trait define the method, that way you ensure that method is implemented & value is set
@blunygeorge
@blunygeorge 2 жыл бұрын
21:16 if we define (edit: define, I meant here as "give definition", implement) the method, of course the class does not have to be abstract. I'm not sure why is that pointed out. I did not try it out, but I assume if we don't define the method, then the class needs to be abstract (if not, and there are no errors, then this could be mentioned, but I don't think that is the case). Sorry for nitpicking.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
You are right but 20:56 is the reason I pointed it out. In the inheritance lesson, when you have at least one abstract method, the class has to be defined as abstract. But in this case, even though we technically have an 'abstract' method we don't need to define the class as abstract because it's coming from a trait & is not defined within the class itself, we just need to implement it. So basically if you have an abstract method in your class that class has to be the abstract class, you can't have a regular class with an abstract method. So that's why I mentioned that when it comes to traits you don't need to mark the class as abstract unless of course, you want to. Just thought it was worth mentioning it in case someone was wondering why we didn't have to declare a class as an abstract since trait code technically gets inserted into the class making that abstract method be part of the class itself.
@blunygeorge
@blunygeorge 2 жыл бұрын
@@ProgramWithGio I wasn't clear originally, by "define the method" I meant "implement the method". If we implement an abstract method, just like in case of real inheritance with extends keyword from a class, the subclass that implements it does not need to be abstract. No difference here between classic inheritance from classes and using traits. That is why it was a bit out of place for me the way you presented it.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Yea and you are correct but some may have had a question on why don't we need to mark the class as abstract since if the class has an abstract method entire class has to be marked as abstract & the way traits kind of work is that trait code is "put" or rather "copied" inside the class that uses that trait, so question could arise that how come class that uses trait whose abstract method is "copied" in the class is not defined as abstract class. Maybe I went too deep with it but just wanted to point it out. But I agree that having an abstract method in trait means that you just have to implement that method or mark the class as abstract just like with regular inheritance. The point I was trying to make is with the way we think of traits that trait code is 'copied' within the class and if you zoom out of it & think of it that way then you could come up with that question. I probably overthought that part & didn't need to point it out but I try to be as detailed as possible to make sure I answer questions that might come up.
@PrabhashChoudhary-o3f
@PrabhashChoudhary-o3f 20 күн бұрын
Hello Gio. For the last example instead of trait, we can have a mail class which can be used without inheritance (extending the class). is that not a good solution?
@ProgramWithGio
@ProgramWithGio 20 күн бұрын
@@PrabhashChoudhary-o3f yes it is. Here I was just demonstrating an use case of traits
@PrabhashChoudhary-o3f
@PrabhashChoudhary-o3f 20 күн бұрын
@@ProgramWithGio ok got it..thank you
@bhaidar
@bhaidar 2 жыл бұрын
Hey Gio, I have two questions here: First, why the use of static::class inside non-static functions? I can use $this and it still works. Any special reason? Second, why would I prefer traits over composition? Thanks
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Hello Bilal, 1. Check the previous lesson about late static binding. It explains why you would use static in certain cases. 2. Composition is almost always better. Traits can help with code reuse, for example, you may have a set of methods that can be part of multiple other classes, you could use traits.
@bhaidar
@bhaidar 2 жыл бұрын
@@ProgramWithGio I already watched the late binding lesson. In this case, there is no inheritance, so using self:: gives almost the same value. Unless I am missing something here :)
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
@@bhaidar are you referring to static::class that's inside trait? It has the same usecase pretty much, if you use inheritance in the class that uses that trait then you would want to use late static binding. In some cases sure it has the same outcome.
@bhaidar
@bhaidar 2 жыл бұрын
@@ProgramWithGio Yes that's what I thought of later. Late Static Binding is useful when there is inheritance. Something else I realized based on my question above, with Traits, functions or properties become part of the class itself. While with composition, you are still forwarding the calls to another class.
@imdadullah9093
@imdadullah9093 Жыл бұрын
do this series have any videos on rest api and how to write good rest apis
@ProgramWithGio
@ProgramWithGio Жыл бұрын
No, we cover the API topic briefly but it's not a full rest API course
@VCR47527
@VCR47527 Жыл бұрын
You present traits as a way to share functionality between classes without using inheritance. What about composing functionality using class properties. In your final example why not use a class MailService which both Invoice and Customer have a reference to?
@ProgramWithGio
@ProgramWithGio Жыл бұрын
For sure, composition is better, we cover composition also in the series. This was just an example of traits
@OleksiiSolonenko
@OleksiiSolonenko 2 жыл бұрын
Why we can’t use composition for email functionality in the last part of video? Just creating class Email without any inheritance and using it where its needed would be enough.
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Yes of course you can. This was just an example of Traits.
@MrKristian252
@MrKristian252 2 жыл бұрын
You know a tutorial is good, when you casually just watch them
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Thank you
@blueyon
@blueyon 4 ай бұрын
PHP does allow multiple inheritance.
@ProgramWithGio
@ProgramWithGio 4 ай бұрын
Not directly, you are referring to ability to implement multiple interfaces & maybe the traits feature.
@user-yx4bo6qo9x
@user-yx4bo6qo9x 2 жыл бұрын
Why didn't we just create an email class with a constructor that accepts the subject, message, sender's address, recipient's address and didn't create an object of this class and didn't call the sendEmail() method from object?
@ProgramWithGio
@ProgramWithGio 2 жыл бұрын
Sure that's another way to do it. This was just an example of how traits can be used.
@substance90
@substance90 11 ай бұрын
31:20 this violates the Single Responsibility Principle. IMHO one would be better off using dependency injection of a MailService in both classes.
@ProgramWithGio
@ProgramWithGio 11 ай бұрын
Ideally yes, this is just an example of Traits, we cover composition later
@ntdash2153
@ntdash2153 2 жыл бұрын
current trait parent
@ProgramWithGio
@ProgramWithGio Жыл бұрын
🤔
@ntdash2153
@ntdash2153 Жыл бұрын
@@ProgramWithGio listing precedences : current class > trait > parent class
@PickleADC
@PickleADC Жыл бұрын
i just prefer using interfaces and design patterns.
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Awesome 💙
@maickelwand9100
@maickelwand9100 4 ай бұрын
I stop every video at the first FooBar nowadays. Made it to 23 minutes this time.
@ProgramWithGio
@ProgramWithGio 4 ай бұрын
Glad you watched the first 23 minutes 💙
@JoseManuelCornelio
@JoseManuelCornelio 6 ай бұрын
I'm totally lost in this one
@ProgramWithGio
@ProgramWithGio 6 ай бұрын
Any specific questions?
@BobDoe_69
@BobDoe_69 Жыл бұрын
is this difficult or am I just st*pid af hmm second guessing myself honestly
@ProgramWithGio
@ProgramWithGio Жыл бұрын
I can tell you that it's not easy, so no you are not st*pid. Don't worry about it if you don't get it on the first run. Take a break & come back to it and rewatch. It can take some time & everyone learns at different pace 💙
@TomiBorchert
@TomiBorchert 3 жыл бұрын
sounds like we are in a hurry.
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
Not sure what you mean. Do you mean that I talk too fast? If that's the case I apologize, I try to talk slow. Though youtube allows you to adjust the playback speed 👍.
@SarkarRipon
@SarkarRipon 11 ай бұрын
Rather you stop teaching online because you are not good at teaching, you’re making a simple thing complicated.
@ProgramWithGio
@ProgramWithGio 11 ай бұрын
Many would disagree with that given the positivity in comments but feel free to watch something else mate. Cheers
@kickass1179
@kickass1179 3 жыл бұрын
Nice explanation, but I hope some viewers don't get you wrong, as I do not see any downsides for Traits. From PHP.net: "PHP implements a way to reuse code called Traits.", it doesn't mention at all that Traits can be used as contracts. Traits SHOULD be used whenever it is necessary to reuse code, it is PHP's way to compensate for being single inheritance language.
@ProgramWithGio
@ProgramWithGio 3 жыл бұрын
For sure, traits are very useful but I've seen them misused which is why I covered it in case you see it misused that way and decided to use it the same way. I don't think anyone would misunderstand since I point out the benefits of it and emphasize that it's good for code reuse. But also I don't think traits should be used for code reuse in certain cases. Sometimes developers drop in code and use it in many different places where it doesn't really make sense domain wise.
@karolzamojcin1886
@karolzamojcin1886 Жыл бұрын
@ProgramWithGio
@ProgramWithGio Жыл бұрын
💙💙
@chenting71
@chenting71 Жыл бұрын
Really enjoying. Great Great Great. By the way, the more I get into PHP OOP, the more I feel its principle and logic become clumsy, chaotic and self conflicting. Like a not been well-thought law kept patching itself. 🥱😅. You opinion is well respected. PHP is still a powerful script language, just hope they can sort things out more logically...
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Thank you. I think OOP makes code cleaner & more organized. It of course depends but overall I think it makes it better
@rustavellyne
@rustavellyne Жыл бұрын
is any difference of using __CLASS__ instead of static::class?
@ProgramWithGio
@ProgramWithGio Жыл бұрын
Yes, the constant gives you the class name where its defined so if you use it in some base class it will return the base class name, while static::class will give you the class name where its called from, so in some cases that might be the child class.
PHP Anonymous Classes - Full PHP 8 Tutorial
7:17
Program With Gio
Рет қаралды 15 М.
When to use Traits, Interfaces, and Abstract Classes in PHP
15:08
Andrew Schmelyun
Рет қаралды 17 М.
A clash of kindness and indifference #shorts
00:17
Fabiosa Best Lifehacks
Рет қаралды 133 МЛН
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 192 МЛН
50 YouTubers Fight For $1,000,000
41:27
MrBeast
Рет қаралды 205 МЛН
Secret Experiment Toothpaste Pt.4 😱 #shorts
00:35
Mr DegrEE
Рет қаралды 28 МЛН
What Is Late Static Binding & How It Works In PHP - Full PHP 8 Tutorial
9:58
PHP 8 3 Released
11:03
ThePrimeTime
Рет қаралды 103 М.
The Flaws of Inheritance
10:01
CodeAesthetic
Рет қаралды 918 М.
PHP traits in depth with examples - OOP in PHP | Part 9
30:53
The Codeholic
Рет қаралды 13 М.
Is PHP the Secret King of Code?
6:42
Stefan Mischook
Рет қаралды 54 М.
The Story of Next.js
12:13
uidotdev
Рет қаралды 558 М.
Rust For PHP Developers
59:42
Nuno Maduro
Рет қаралды 25 М.
PHP doesn't suck (anymore)
10:48
Aaron Francis
Рет қаралды 201 М.
Java's Creators Rejected Multiple Inheritance - Here's Why
13:14
Coding with John
Рет қаралды 68 М.
A clash of kindness and indifference #shorts
00:17
Fabiosa Best Lifehacks
Рет қаралды 133 МЛН