Learn Object Oriented PHP - 2 hour Object Oriented Programming Lesson For Beginners | PHP OOP

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to learn object-oriented php with myself gary clark and in this first recording i'm going to get us off to a good start by answering the questions what are objects and how do we create them the easiest way for me to explain to you what objects are is to simply show you the good news is you're already familiar with thousands of objects because there are visual representations of them all over the applications websites software that you use every day in the simplest explanation they're basically the things that make up an application let's have a look at an example and i'll show you what i mean by that so i'm only going to use examples which you might be familiar with here's amazon this is my amazon account i'm able to sign into my amazon account because i'm a customer and a customer is an object up in the top right hand corner there you'll see my basket a basket is also an object here's some products products are also objects they are the representations of things or rather i should say they are the data representation of things and the beauty of object-oriented programming is that we can take these objects and we can give them characteristics and also the ability to do things so as you can see there is displaying my name the products all have names and they all have prices as a customer which is an object i can select a product and place it in a basket these names these characteristics and these pieces of functionality are all associated with the object and they all live with the object in this first recording we're going to replicate a fairly well-known type of object and that is a twitter user so here is my twitter profile and as you can see there's various pieces of data there it's got name username location etc in php or an object oriented php we refer to these pieces of data as properties or class properties in other object-oriented programming languages are often referred to as attributes you can interchange the two they both mean the same thing so as you can see here our properties are name username bio location and join date so that's enough talking this course is more about doing so follow along with me i've created a folder called oophp in my editor inside of that i've created a folder called chapter one and inside of that i'm creating a new php file called creating hyphen objects i'm using phpstorm so as you can see my opening php tag has been done for me use whichever editor you want i'm not using any of the fancy features i'm literally just going to be using this as a code editor so how do we create objects where do they come from in order to create objects we need something called a class and a class if you like is a blueprint a mold it's a specification which tells us what characteristics and what functionality our object should have a class is created like this we have the class keyword followed by the name of the class in our case a user and you uppercase the first letter and then you follow that with opening and closing curly braces then you need to define whatever properties your class should have the way you do that is you put a visibility keyword which could be public protected or private followed by a variable name so in our case we're going to have name we're going to have a username i think we'll have a follow account just to give us a slight variation from using strings don't get too hung up on the visibility keywords public protected and private for the time being at the moment we're just going to use public because that's the least restrictive now let's create an object from this class as you can see i'm outside of the classes curly braces now typically you won't actually create an object in the same file as your class files but this is just for demonstration purposes and so i've created a variable called gary object and then i'm making an assignment so i use the new keyword which is used for creating objects from classes i specify the class name user and then opening and closing parentheses which in this case are optional but will not get into that in too much detail and this creates a user object which i assigned to the gary object variable this action can be referred to as creating an object or instantiating a class because we're creating an instance of that class let's examine this newly created object and we can do that using the print underscore r function which allows us to print out the object in a human readable way so i'm moving into the chapter one folder of my project folder and i'm going to start up php's local server you can do this using php hyphen capital s localhost colon and then any port number i usually choose 8000 or 8080 so i'll copy that go over to the browser and i just paste in that and append creating objects.php onto the end of it because that's the name of our file so here we go it says we have a user object and then it lists out our properties so we're getting somewhere but that's not very helpful because we didn't give our properties any values i think if we go back to the code give our properties some values and then come back then they'll be a bit more meaningful so let me show you how to assign values to properties and we use this thing here it's called the object operator it's basically a hyphen and a right bracket we follow that with the property variable and you'll notice that we dropped the dollar sign of the beginning of that and then the way we assign this is the way we assign any variable we use equal sign and then just the value so we'll do that for name username and for our follower count once we round off this last one then we do the same as what we did before using the print underscore r function where you just print out that object in a human readable fashion and then let's go back to the browser and give it a refresh and see what we come up with and so there you go now it's saying we have a user object the name property is gary clark the username property has a value of gary clark tech and the follow account has a value of 50. now it's over to you to get your hands dirty and give this a call yourself here's a reminder of the steps so i want you to instantiate a new user object name the variable after yourself set the name username and follow account properties and then use the print r function to check that you've created it correctly and check your work in the browser so give it a go here's my solution so say for example your name was john smith this is how we would have done it so john object equals new user and opening and closing parentheses and then same as we did for my name username or follow account we just assign these properties we do that in the same way that we assign any value to a variable we use the assignment operator otherwise known as the equal sign and then all we're doing here is we're just going to print that out over to the browser and there you go so the name has a value of john smith username has a value of at john smith and follow count is 1000 in the previous recording we had a look at what objects are and we established that objects could hold the pieces of data which were referred to as properties and this one we're going to have a look at object functionality when you add functions to an object we call them methods and that's what we're going to do in this recording so i'm in exactly the same folder as where i left off in the previous recording but i've created a new php file called defining methods and for now just create opening php tags then we're going to go back to amazon and have a look at another object so i've just added this item to the basket and clicking proceed to checkout and here is the basket so we've got two properties that we're going to examine items and there's a cost so we're going to call it item cost or something like that and postage unpacking which will probably end up calling shipping cost or something like that so what i want you to do now is this create a basket class add an item's total and shipping cost public properties instantiate a basket using the new keyword instantiate just means create a basket and instantiate it's saying that you're creating an instance of a basket set values for both properties and then just far dump your work and go and check it out in the browser just like before i recommend that you do all the practical exercises i set you this is how you learn here's my solution so i'm creating a basket using the word class and then basket with an uppercase b opening and closing curly braces what i'll show you here is that the opening brace can go on the next line and that is the modern convention which you'll probably see more these days next what i'm going to do is i'm going to create the properties so two public properties one called items total and i'll use camelcase to do that but don't get too hung upon conventions and things like that at this stage in your development shipping cost and so all we need to do now is instantiate a basket and set some properties sorry it's basket equals new basket and we just set our properties like so which hopefully you should have remembered from the previous recording basket right arrow items total equals and let's just set any numerical value for that and you do exactly the same thing for shipping cost so basket right arrow also known as object operator shipping cost equals 10 and then all we're gonna do is just dump that out and make sure that those values have been set so far underscore dump and we'll just look at the whole basket remember we've got to change our url so it's localhostdefiningmethods.php and there you have it so we have an object that object is a basket and has an items total of 50 and a shipping cost of 10. hopefully that stuff should be sinking in now the purpose of that exercise was really to get us up to this point where we are now so we have a basket has a couple of properties what i want to do now is give the basket the functionality to calculate a subtotal using these properties and the way i do that is i add a public function so like we gave our properties the public keyword you do exactly the same thing with your methods which quite confusingly are called function so even though we refer to them as methods we create them just like we do with other functions by using the function word and we're going to call this calculate subtotal in order to access an object's properties from within an object's methods we use the this keyword which is a dollar sign followed by the word of this and what this refers to is the actual class itself so he's saying this basket and then you use the object operator like we did to access the properties from outside the class and then we just access the properties like we did before so this items total plus this shipping cost will give us the subtotal which we're looking for now i'll show you how you call that method using the object so i'll just create a little bit of space for myself here and you do it in exactly the same way as how you access a property so we say basket right arrow and then calculate sub total what do you think will happen if we check that out in the browser now that's a quick look blank screen because we haven't actually returned a value from the method so in order to do that i'm going to store the sum of these two values in a variable called subtotal and then all i need to do is drop down a line and just return that subtotal and then that will make this method a lot more useful to us and we can view the output of that by just var dumping basket calculate subtotal and so if you see we've got an items total of 50 and a shipping cost of 10 so hopefully we should see a value of 60 when we go back to the browser and refresh and there you go so far so good and of course what is more common is that you would store the actual return value in another variable so we'll do that now subtotal equals basket calculate subtotal and we'll just far dump that and have a look at that just to make sure or just to prove that that is how this works and we'll just go back to the browser quick refresh everything's still the same there now it's your turn what we need to do is add a public discount property and then rewrite this line so that the discount is deducted set a discount value of 30 then all you need to do is follow dump the subtotal and go to the browser and check that you've got the correct value you should get a value of 30. so here's my solution public discount uh it's just really basic maths you just minus the discount from this so it's this right arrow discount because you're accessing an object property from within a method i'm just deleting the comments as we go along just to remove a bit of noise from the code and then we set a discount value of 30. this should be all very straightforward to you by now so 50 plus 10 minus 30 should equal 30. let's go back to the browser and refresh and there you go 30. so how did you get on with that and are you enjoying object oriented php so far hopefully things are starting to make sense to you and it's all starting to fit into place in the next recording what we're going to do is we're going to have a look at spotify and we're going to start making objects interact with each other by taking a song object and adding it to a playlist object finally going to start taking a look at object interaction and it's the interaction between objects which really started to make object-oriented programming click for me it all suddenly made sense and what i've done up to that point just seems so unnecessarily complicated hopefully i'm going to demonstrate that to you i'm going to take a real world application and use a real world example of objects interacting with each other i think you're going to really enjoy this one and hopefully this is where the stuff will really start to click for you let's get things started by creating a new file for this section which i'll call object interaction and i'm in the same folder as what i did for the first two recordings chapter one and i'll just start by doing my opening php tags but nothing further and we'll go and have a look at what we're gonna do so here's spotify this is my brother's rock playlist and guess what our playlist is an object just take a second to see what properties that playlist object might have and dc any other objects on the page i'm scrolling down through my brother's playlist and i've noticed that there are no octopus theme songs on here so i'm going to go over to the beatles classic abbey road i'm going to take a song object octopus garden and i'm just going to drag that and add it to my brother's rock playlist and they'll be absolutely delighted with that and in this recording what we're going to do is recreate what i just did we're going to take a song object and add it to a playlist object so first off we need to create a song class create song id and title public properties instantiate an octopuses garden song using the new keyword and then check in the browser so here's my solution if you'd rather pause it and have a go at it yourself first then by all means do that and what i would preach is practice practice practice so that would be an excellent idea very simple one to do this so we just create a class with a public property called song id and a public property called title so internally spotify will have a song id for each song will have a unique identifier and so that's what i mean by that and for this we'll just use a numerical value so in order to create our song object i'm just going to create a variable called octopus song then i do equals new song opening and closing parentheses i just need to set the two properties i'll do that by saying octopus song right arrow property one octopus song right arrow property two which are song id and title respectively so i'll just get a song id of one and obviously the title is octopuses garden so i'll use double quotes because there's a single quote in the title great stuff so we just need to var dump that and then go and check our browser remember we've created a new file so we need to give it a new file name which is object interaction.php if you've got your server set up the same way as what i have and so there you go we have an object object as a song is the song idea of one and the title of octopus's garden so hopefully you should have found that fairly straightforward by now what i want to do next is go back to spotify and just take another look at the playlist object and try and pick out some properties so here we have one the playlist has a name what others can you see because here's quite a big one the playlist has songs and we call this composition because we've already said that song is an object we've said that players is an object and now we're saying that we can add a song object to a playlist object and if you think about that and the opportunities it presents us this is huge let's create a playlist now so i'll give it a couple of public properties and the first one will be name and the second one will be songs plural no one said that properties had to be singular so i'm going to give it a name of songs and i'm also going to set it to an empty array and that is really just to demonstrate an intention this is what i expect songs to be so we'll go into setting default values and type hinting and stuff like that later on but for now this is just to say this is what i expect the song's property to be an array so i'll create a new playlist playlist equals new playlist i'm just going to dump out the songs property on the playlist object just to demonstrate and what happens when you set a property to an empty array so i'll comment out the octopus song if i don't so we don't see that refresh and so as you can see our playlist songs property starts off as an empty array the zero means it has no length there are no items inside it but let's change that now i'm going to create a method which will take a song and add it to the songs array so public function add song always use descriptive names don't just put something like ad ad what make sure another developer could read this and know exactly what's going on and so in order to add a song to the songs array first things first we're actually going to need a song so we'll pass a song in to the method as an argument and that will be a song object and then in order to add it to the songs array we say this as in this keyword this songs opening and closing brackets so adding an element to an array inside a method is just the same as adding it to any other array variable that's all we need to do that method we're not returning any value all we're doing is adding the song to an array so let's give our playlist some properties first of all we'll give it a name and we just called it rock and then we're going to call our add song method so playlist right arrow to call a method add song then we need to go and get a song object so i'll copy this octopus song variable here i'll pass that in and that's it that should be all we need to do in order to add a song to the playlist all right should we go and have a look what we've got so i'm going to dump out i'll dump out the playlist object and we'll take a look at the entire thing and see what we've got so i've done playlist over to the browser okay so quite a bit of information on the screen there but just glancing i see that we have an object which is a playlist has a name property and a songs property which is an array it's a bit messy so what we'll do is we'll actually go back and we shall just dump out the songs property so we can have a closer look at that so far done playlists right arrow songs back to the browser for a refresh and there we go we have an array with one item which is a song object song id1 title is octopus's garden perfect now it's your turn instantiate a song object set a song id and title and then add the song to the rock playlist i think you can do that i'm pretty sure you come by now i'd encourage you to always do the practicals i know i say this and i'm like a stuck record but it really will help here's my solution so i'm going to stay with an underwater theme yellow submarine equals new song then what i need to do is set a song id and title so yellow submarine right arrow song id let's give it number two because i call it octopuses garden number one title equals yellow submarine and then in order to add it to the playlist it's just playlist right arrow add song and then you pass in the yellow submarine when i refresh the browser now i can see that my songs property or the songs array has grown it's got an extra item in there now which is also an object and that object is a song so i'll put it down on its own line hopefully that makes it a little easier for you to read so we have a object which is a song has a song id of two and the title is yellow submarine hopefully you got the same as me if you got a different result if you or if you got any errors make sure you go back and check your code against mine and don't be too worried about making errors making errors is really how you learn this stuff you need to make hundreds and hundreds of errors before you can do this stuff professionally so the more areas you get out of your system now the better that is believe it or not so that brings us to the end of this recording we've covered quite a bit of ground there we've done some object interaction as well as learning about composition ie setting objects as properties on other objects in addition to stuff that you should already be getting quite comfortable now such as adding arguments to methods and using this keyword etc so you're making good progress my friend let's keep this momentum going in the next one where we'll level things up once again in this recording we're going to look at a special method called the constructor and what i've decided to do from this point forward is to keep the classes and the logic separate in separate files which is good programming practice so i've created a chapter two folder which is inside the oophp folder and in there i've started out by creating a constructors php file so if you get yourself up to this point all i'm going to do to start off is create an empty web page so if you're using visual studio code like me you can just do exclamation mark and then tab and it'll produce an empty html page otherwise just do an opening and closing html tags and also body tags and inside there i've got opening and closing php tags anyway this is the example i'm going to use for this particular one this is the discussion tab on my youtube page as you can see it's made up of comments which are various properties such as text and you have a user you have a date or time when it was posted various little things such as thumbs up like thumbs down and the base my initial work around this text property as that is what you could say is the primary property for a comment and so in the same folder the chapter 2 folder i'm now going to create a comment class and this will be dedicated just to holding the comment class and its properties methods etc and no other php code will go in there so comment php we need our opening php tags and we've created classes before all you need to do is use the class keyword and comment opening and closing braces then we'll add that text property and after that we'll add a constructor method so what is one of those here's a description from someone that i learned from you'll use constructors to do whatever should always be done and done first when an object of this class is made so what we're saying is that whenever you say new comment then the constructor method will be called and whatever code is inside that constructor method will be executed the way we create constructor is like this two underscores so underscore underscore construct opening and closing brackets and then the rest of it is just like any other method and we call the constructor a magic method so it's one of a series of special php methods and what i'm doing here is setting the text property of the comment so thinking of the description i've just shown you whatever should be done and done first i think it's fair to say that a comment will always need some text so that should always be done whether it should be done first is arguable but this is a pretty good use case and a fairly realistic one so we pass it text into the constructor and then we set that property using that variable and this is easily the most common usage of constructors that you'll see i.e setting properties on objects occasionally you'll call another method but setting properties is your main one let's now go over to constructor's php and we'll this is where we're going to add our logic so first we need to pull in the comment class and we do that by requiring the comment php file and then what we're going to do is create a comment so comment equals new comment and if you recall from our previous objects that were created we've got these opening and closing parentheses and you've probably wondered what they're for so this is where we actually pass in our constructor arguments so if we didn't have any constructor arguments we wouldn't actually need these parentheses but it's quite a common practice to include them anyway even if they're empty so what we're going to do here is pass in our comment text so just make up anything this is some comment text will do then all we're going to do to demonstrate this is just echo out the text property on our newly created comment object so echo comment right arrow text then i'm going to go and make sure that my server is running so if you're doing the same as me i'm going to move from the old php folder into the chapter 2 folder and then i'm going to start up my php's built-in server and you can copy the command that you see on the screen which is php hyphen capital s localhost colon 8000 which i'll copy and paste in followed by forward slash constructors dot php and there we go so there's our echoed text i'll bump it up so you can see it this is some comment text so far so good now it's your turn to have a little go obviously they'll need to be some way of connecting the comment to a user and the way we're going to do it is by having a user id attribute which will be numeric an attribute just means the same thing as property could also be called class variable so we'll add the user id to the comment constructor as a second parameter and then when we instantiate the comment we need to include the user id when we pass it into the opening closing parentheses then we just need to remove the echo statement and i want you to add a paragraph where you echo out the text and the user id and then go and check your work in the browser so here's my solution i'd encourage you to give it a go but here's what you need to do so i've took my comments and i've painted them because i like to keep track of what i'm doing first we need to create a public property for the user id i'll delete my comments as i go along my instructions then you pass that into the constructor as the second parameter and obviously you need to set the user id property to that variable all very straightforward and you'll do this stuff day in day out a lot of times it doesn't get any more complicated than this so this user id equals user id again we'll clean up our comments and now we just need to go over to the constructor's php file which is where we add our logic and all we're saying here is that we want to remove the echo statement and actually create a paragraph in the html so we'll add our second argument so we're just going to give it a user id of 10 so you pass that into the parentheses as the second parameter and then we're going to move outside of the opening and closing php tags and create a paragraph and so i'm echoing out the comment text then i want to use our new user id property so and then same again here i'm just going to call that out so comment right arrow user id that's all we need to do back to the browser give that a refresh this is some comment text by 10 so we'll change that to buy a user 10 give that a refresh excellent so just a quick recap in case that went a bit fast so comment text the text was passed into our comment constructor as the first argument then we said by user and then we echoed out current user id and the user id was passed in as the second argument and so like i said about constructors they are used to do whatever should be done and done first so it's fair to say that you'll always need to say who owns the comments i who created a comment and a comment will always need some text so this is a very good example of a constructed usage in the next one i'm going to introduce inheritance which is a vital concept in object oriented programming and it's one of the things that makes it so effective one of the ways in which objects make programming more efficient is the ability to use one class as the basis for other classes in other words our objects and classes can inherit from parents inherit attributes from parents in the same way that humans can inherit attributes from parents those attributes as far as we're concerned in objective programming we've already seen them they are properties and methods that's what we're going to look at in this recording we're going to take this account class and extend it with child classes which inherit its properties and methods so here is our account class again and we are going to extend it with a checking account as you can see the checking account inherits all the base properties and methods without us having to explicitly declare them when we actually create the class but not only that the checking account can then declare its own properties in methods for example it can have a transfer method which might be something which is unique to a checking account other accounts might not have this functionality so by doing this we're saying that it will inherit all the base features of the parent but it can also have little characteristics properties and methods which also make it unique so let's make a start i'm in the chapter 2 folder and i'm creating a class which will be account.php and i'm just going to add those properties and methods which we saw on the diagram and these will be available to all the classes which inherit from this account so we'll have a public property called account number we'll have a public property called balance and then we need to add our three methods so we're not going full functionality to our methods we're just going to echo stuff out just to illustrate what is actually happening so for the deposit we'll pass an argument of amount and then what we'll do is we'll just echo depositing whatever the amount is and we'll do exactly the same thing for withdraw and for the get balance what we'll do is we'll just return the balance so i've taken the liberty of speeding through the editing a bit there as you can see withdraw follows the same pattern and get balance just returns this balance so in order to demonstrate this in the browser what i'll do is i'll create a file called inheritance.php let's change the title to inheritance just to be thorough and then what i'm going to do is add my opening and closing php tag i'm going to require the account file and i'll also create an account class and all i'm doing here is just an initial setup just to call these methods on the account class and then i'll demonstrate that we can call the exact same methods on a child of the account class so deposit and we'll pass in just nominal amounts 20 and we'll call withdraw and we'll pass in 10 and then all we need to do is go over to the browser i appended houston's php onto localhost and there we go depositing 20 withdrawing 10. so exactly what we expected now let's go and create a child class of the account class and i'll call it checking account so checkingaccount.php and the way that we inherit is we use the extends keyword so class checking account extends account we'll need to require the account class so we use require once typically that's what you'll use when you're reporting class files into another one now because checking account is extending or inheriting from the account class we don't actually need to explicitly define any properties or methods here those properties and methods will be automatically available to the checking account so in inheritance php let's require checking account we'll create a new checking account and what i'll do is i'll just change the name of account to checking account for these last two methods here i can actually do both of those at once now because i'm using phpstorm for this recording and so as you can see we're using the exact same method as what we did for the account we've not defined any new methods in our checking account when i refresh everything works exactly the same still let's now go ahead and add that transfer method which if you recall from the diagram we said this would be a unique method to the checking account other accounts might not have this kind of functionality and so following the same pattern as we did for our withdrawal deposit methods we're just going to pass in an amount argument and then we'll just echo out transferring x amount just for demonstration purposes and in our inheritance php file we just need to call that method so checking account to transfer and we'll just say 100 here over to the browser refresh and there you go now this should be obvious to you but before i move on i just want to demonstrate that this transfer method will not be available in the parent class it's only available in the child class so over in inheritance.php let's remove these references to checking account change them to our account class i'll just rename these to account then we need to go over to the browser refresh so the first two deposit and withdrawal work okay but when we try and call transfer that's not available to us okay check out this diagram what i'm illustrating here is that there is no limit to the levels of inheritance you can inherit as many times as you like and also horizontally you can have as many classes inherit from the one class as you like so that's what we're going to demonstrate in this next part by extending the checking account with a premium checking account and i'm going to let you have a go at this so here's the instructions create a premium checking account class which extends checking account give it a public minimum balance property and also give that a default value echo out the premium checking account minimum balance in inheritance.php and then call all of the methods which it inherits also do that in inheritance.php so hopefully you should be okay with that here's my solution so first thing i need to do is create the premium checking account class which i do like this and then that needs to extend checking account i need to require once the checkinggitcount.php file and all we're doing is just adding one public property called minimum balance and we're going to set a default value so that we can echo that out and we'll just call it 5000 so for a premium checking account that's probably a fairly realistic example the thing that would make it unique is it would have like a minimum balance so in our inheritance php file we're requiring premium checking account.php create the premium checking account echo out the premium chicken cap in my balance and then call all of the other methods that it's going to inherit and as you recall we didn't actually define the properties and methods in the checking account so it's actually inheriting all properties and methods from the grandpa from the account via the checking account so i'll zoom through that a bit let's refresh and there you go so recording now minimum balance at 5000 are also calling all the methods that have been inherited deposit withdraw transfer that all works so i hope that that was clear you don't have to try and memorize this because inheritance is so common in object-oriented programming it's something that we're going to cover over and over again in this recording we're going to look at visibility and scope so we're going to look at public private and protected properties i'll explain each one and how they differ and i'll explain the rules which apply to each and we'll have practical demonstrations for each one leaving you with complete understanding of the concepts so this is how visibility works our most restricted level we have private properties and methods they can be accessed in the defining class only they cannot be accessed in child classes and they cannot be accessed of object instances moving the scope outwards we have protective properties and methods they can be accessed in the defining class and subclasses only they cannot be accessed of object instances anywhere i.e they can't be accessed anywhere outside of a class finally our least restrictive properties and methods are public they can be accessed in any class and anywhere in the code so there's schoolwork don't be intimidated by the theory because the practice is where it will all make sense and let's do that now so i'll start off by creating a new class and what i'll have is a file reader which will be a parent class for readers of different types of files for example in this one we'll have a csv file reader so it's quite a common thing to have in php you create a class which wraps around php's inbuilt functions for reading different types of files and that's the kind of thing we're creating here so class file reader i'll give it one public property and we'll go through each level i'll demonstrate public first protected and then private and we'll see what is allowed and what is not allowed for each one so we'll create a just a standard php file not a class uh called visibility.php and this is where we're gonna have our html which will display to the browser to show our values so i'll just give it a title of visibility and what i need to do is add my php tags i need to require the file reader class or the file reader file so require filereader.php and then we just need to create a new file reader so file reader equals new file reader and then we'll create some html and we'll echo out the uh value of the data property so php tags echo and file reader and so we're going to use the right arrow and access the data property directly which we can do because it's a public property and there's a rule can be accessed in any class and anywhere in the code over to the browser visibility.php and there we go some random data i'll just pump this up so you can see it so you shouldn't have seen anything that surprised you there here's a little challenge for you to try out make this property protected and then go and test it out in the browser what do you expect to see give that a go i'll show you what happens now so change it to protected over to the browser refresh on court error cannot access protected property file reader data so because it's a protected property we can't just access it anywhere and phpstorm is actually telling us this because down the bottom corner is saying member has protected access there is however a way that we can gain access and we do it like this i create a public function i'm going to call it getdata but you can call it whatever you want and all i'm doing is returning this data let's have a look at the rule the rule is that protected can be accessed in this class and subclasses only so we're accessing it within the class and in order to display that to the browser i just say file reader get data give that refresh and there you go let's delete this now and we'll try out something else so the rule tells us that we can access it in child classes also let's test that theory out we'll create a child class and we'll call it csv file reader so this is a class designed for reading csv files and it's gonna extend file reader and because it extends file reader it should inherit that data property which we should be able to access so we'll create a method called getdata in this class now and all we're going to do is return this data so as we're extending file reader we're going to need to require it so require once file reader dot php and we'll just take a look at the rule again protected can be accessed in this class and subclasses this is a subclass so this should work let's make some changes to visibility.php so we're using csv file reader instead of file reader so we'll require it and then we'll change this to csp file reader just to be explicit and obviously we need to change the cluster csv file reader and we'll change this final reference here to csv file reader over to the browser refresh still working exactly the same so prove that that you can access protected properties in subclasses let's change this to private now and what do you expect would happen if we went back to the browser and refreshed so if we look at csv file reader member has private access so it's given us a warning here to tell us that it probably won't work and there you go but our error message is different told us that the property is undefined as in the csv file reader has no knowledge of the data property so let's look at the rule cannot be accessed in child classes they can only be accessed in the classes that define them so that's what we'll do over to file reader can be accessed in this class only let's test that out so we'll go over to visibility.php and we'll just change everything back from csv file reader to file reader and then once we've done that we just need to go back to the browser and that works because we've accessed the data property in the class that defined it and that's the only place where you can access private properties so quick recap public properties methods can be accessed in any class and anywhere in the code protected can be accessed in this class and subclasses only cannot be accessed of object instances anywhere and private properties and methods can be accessed in this class only cannot be accessed in child classes and cannot be accessed off object instances just anywhere in the code so as always you don't have to try and memorize this stuff because we're going to repeat it so many times that by time we get to the intermediate stuff this will be second nature to you anyway okay let's keep mixing it up in this one i'm going to use an ebay auction for our example um no doubt that you're familiar with how it works you have a current bid and then you have to enter a minimum bid in order for your bid to be accepted for something i think this is something that we should be able to hook into in order to demonstrate encapsulation and getters and setters so i've created a bid class and here's our opening php tags and class is called bid and what i'll do is i'll start off with a private uh attribute called minimum bid and i'm gonna set a default on this which is fairly unrealistic but it's just for demo purposes only otherwise i'd have to write a ton more code just to demonstrate something which shouldn't be that complex and i'm going to add a public property called bid amount and the reason i'm adding a public property is to demonstrate uh some of the consequences if your properties can be unwantedly modified by other parts of your program i'm creating an encapsulation.php file in order to demonstrate our logic and display in the browser so i'm requiring the bid.php file and all i'm doing is just creating a new bid so bid equals new bid and then what i'm going to do is i'm going to set a bid amount to a value which is actually less than the minimum bid amount and because this is a public property there's nothing preventing me from doing this so what do you think is going to be the outcome let's echo something out to the browser and see what has happened so the bid amount is and then it will just depend on the actual bid amount which we can access we can set it and we can also access it because it's a public property okay let's go over to the console and start my server if yours is already running that's okay and i do that using a php built-in server with php hyphen capital s localhost and then call on any port number you want usually 8 000 or something over to the browser localhost 8080 encapsulation and there you go the bid amount is four so i've been able to set the bid amount to something which is less than the minimum bid which isn't good we don't have protection so how do we go about putting that protection in place well the first thing i'm going to do is i'm going to change this public property to private then i'll go back to the browser and there we go so we get an error so even though we get an error that's good because it means we can't modify this unwantedly the way that we will modify it and the only way that we'll be able to modify it is by using a special cl method called a setter and we're going to call it set bid amount that will take one argument which is the amount that we wish to set and our bid amount gets set to that amount which is being passed in so this right arrow bid amount equals amount so whilst we're setting the bid amount to the amount we still don't have any protection our minimum bid is still can still be set to an amount which is lower so the way that we tackle this is we do a check before we set that amount so if the amount is less than the minimum bid amount then what we would do in real life is probably throw an exception but we haven't actually covered exceptions yet so we ain't going to do that what we're going to do is if the amount is less than the minimum bid amount we're actually going to set the bid amount to the minimum bid amount so that'll teach the user to attempt to put in bogus numbers so how should we handle if the amount is okay your first instinct might be to do this to just put an else conditional in there so if the amount is less than minimum bid the bid amount gets set to the minimum bid else the bid amount gets set to the amount i prefer to keep my conditionals to a minimum because the more of them you have in there the harder they are to and the harder it is for another developer to follow the logic what i'd prefer to do in this situation is just return so if the amount is less than minimum bid amount set the bid amount to the minimum bid and then just return and that breaks out the function you're done if however this condition isn't met the amount is good then that gets completely ignored that block there and all we do is we just set the bid amount to the amount okay let's put this to let's put this into practice so bid set bid amount and we'll keep with the same value 4 again so that should match the condition that we specified in our if block we've also got this display part here so this isn't actually going to work because bid amount is private so here's a quick challenge for you how do you suppose we should modify our two files in order to display the bid amount in encapsulation.php use your intuition and give it a go here's the solution we create a getter so where we have a setter we also can create a getter and all that the getter does is just returns the value it's a public method which returns a value so public function get bid amount return this bid amount and then what we have to do is go over to encapsulation.php and instead of just accessing the property we access the getter and that will work over to the browser give it a go encapsulation.php the bid amount is five so we tried to set it to four that's going to force our if conditional to be true because the amount is less than the minimum bid amount and the minimum bid amount is five so we set the bid amount to the minimum bid amount if however we set it to a value which is equal to or above the minimum bid amount so if we set it to 10 now go over to the browser and that's happy to set that to that amount so this conditional is false and this line here gets executed instead because the amount was 10. so that was encapsulation the bundling of data with the methods that operate on that data if we want to modify the data we use setters and if we want to access the data we use getters so the functionality is defined all in one place and not in multiple places the functionality is defined in a logical place ie in the same place as where the data is kept and the data in our object can't be unexpectedly modified by code outside the class which as you saw can cause problems welcome to this final recording of the chapter and well done for making it this far you're making really good progress this one's about abstraction which is another one of the four pillars of object oriented programming i'm going to be approaching it from a high level initially and we'll get into it in more detail and more depth as the course progresses so first of all what is abstraction if you look around the web you'll see various definitions this is probably my favorite and it's the one which applies most to us as far as this course is concerned obstruction is the process of hiding the internal data and the implementation from the outside world so if i tell you why we use it then it should make a lot more sense we use it in order to provide an interface which is as simple as you can make it so let me illustrate using a high level example think about when you use the internet when you load a web page in your browser there's a lot of complexity which goes on behind the scenes which you don't see for example with this airbnb page i'm using airbnb because we're going to use that in a core example shortly but when you request this page there could be loads of stuff happening for example here we've got data so it's obviously creating a database we can see a search bar at the top search is massively complex so it's probably caching some data in memory to assist with that we've got images images most likely stored with a third-party service like amazon you've got your css and your javascript which are probably working to display um things differently on the desktop than on a mobile phone and also almost certainly showing you different content on different devices for example the images you see on the desktop will be the same versions of different images of what i would send you on a mobile phone where it would use smaller images so massive massive complexity but you don't need to know any of that and you don't get to see any of that all you need to do is click on a link or put an address in your address bar and from a high level that is what abstraction does it hides away the details and gives you a simple interface a simple user experience so let's have a go now at turning this concept into code what we're going to do is we're going to create a reservation class as in an airbnb reservation and we're going to in this scenario we're just going to cancel our reservation and think about all the things which might be involved in doing that action so um in the same folder chapter 2 i've created a reservation.php file i'm just creating a class reservation so imagine now you're another developer you're working on an airbnb site and you need to put a cancellation form on the front end the only thing on the back end that your form will interact with is this one public method on the reservation class which is to cancel that's all you need to do all you would do is just call this method cancel and everything will be handled for you so apart from the obvious things such as updating the database to show that the reservation is cancelled let's have a think about all the other things which might be involved with software development there's always a lot more to it than meets the eye even to the people that are writing the software usually so we might want to check whether cancellation is an actual option in the first place we may want to refund the guest if you think about refunds there might be like a lot of complex logic involved in that it might be fully refundable it might be partly fundable might not be a refundable reservation and also on the subject of refund i guess you need to have a guest in the first place so we're going to have a guest class involved so you can see now complexity is building up and this is just a couple of things i need to make the room available again because once you reserve the room obviously no one else can book it now you're making it available again obviously you need to update the database to say that so it starts appearing in listings again and you're going to need a room class think about the real world you're going to need to notify the host but how are you going to notify them you might have different rules for um what methods you use to notify them depending on how close you are to the um reservation date being fulfilled for example if it's like a week in the future you might just send them a notification in the app but think about what if you're on the day do you send them an email do you send them an sms these are all considerations and behind each one there's different levels of complexity so here we're going to need classes for a notification as well as for email and sms and speaking of email and sms they're likely to be third-party delivery services that you're using which your app will have to communicate with you're also going to need to send a confirmation to the guest i could go on and on this list could get really long and in real life it will be but we'll leave it there and we'll start to implement a couple of these things not all of them so up until this point you've probably noticed that i've only actually used private properties i've not used any private methods and i've sort of held them back in order to help illustrate this point so what we're going to do here was just add a couple of private methods for the sending of a cancellation notification to the host and also for refunding the guest and so the reason that these are private and so that they can't be accessed from the outside world the only thing that the client code has to work with is the cancel function calls that function everything gets taken care of nice simple interface mission complete keeps our code nice and modular and each module doesn't need to know how the other modules implement that functionality it just needs to be able to call upon that functionality and as you'll see later on in the course we'll show how we can switch modules out for different ones which perform the function but slightly different i'll introduce abstract classes abstract methods and interfaces which are all tools which we use to keep our code abstract and flexible it's all part of abstraction so i've now created my two private methods in order to send a cancellation notification to the host we're going to need a host so like i said earlier we would use a host class rather than create that i'm just going to fake it for demonstration purposes just to keep us focused so we'll pretend that this is a host class and in order to refund a guest you would need a guest class going to do exactly the same thing so i'm creating a private guest property which represents a in this case imaginary guest class what we'll just use is a string to represent that guest class and then what i'll do is i'll just write some placeholder code to show that we're sending a cancellation notification and that we're refunding the guest and like i say the functionality for performing these functions it could be very very complex it could be all sorts of things all the classes being called and other methods but as far as our client code is concerned we don't need to know all we need to know is that we just call the cancel method and all of this will happen at the moment we're looking really at the what and how when we get further on into the course we start looking at the where when and the why i'll encourage you to think about how you'd like the code to be used by other developers before we write it i find that writing code like that really helps me helps me stay abstract helps me make a simple interface for other developers and they're really the most important people forget the end users you're writing code for other developers always keep that at the back you mind and you'll naturally write better code okay we're going to need to try this stuff out so what i'm doing is i'm creating a abstract hyphen basic.php file in the chapter 2 folder this is going to be html page so create html and body tags opening and closing php tags and then we just want to try out our code and all we're going to do is we'll require our reservation class and we're just going to call the cancel method on a reservation object so require reservation.php and i'll new up a reservation object so reservation equals new reservation and all i need to do is just call cancel on the object and all that's going to do in this case is just print out those lines that we added to each of those methods let's just go and remind ourselves what we put so we're sending notification to this host so that will be a string in this case we'll add our break tags and just copy and paste that to this one here as well and then we're saying refunding this guest so we need to call those methods from our public cancel method and i just need to append on obstruction hyphen basic because we're going to go into this in a lot more detail and they go sending notification to host class refunding guest class and just to be thorough i'll add an extra line here which just reminds us that there's a ton of other stuff that's also going to happen which makes up part of canceling a reservation change these quotes for double quotes because i'm putting in a uh single quote there and a lot of other stuff that you don't need to know about and there you go and a lot of other stuff that you don't need to know about so that covers your introduction to abstraction and it also brings us to the end of chapter two and sincerely well done for sticking with it this far in this recording i'm going to look at object and class data in php so i'm talking about properties class constants and static properties i'll show you how they're defined and i'll demonstrate some practical uses of all three going beyond that i'll also cover some of the other stuff including what is and isn't allowed and i'll finish off with some typed properties the way i'm going to start off here is with a brand new chapter 3 folder and inside of that i'm creating a file called calendar.php which will hold a calendar class and i think this should be pretty good for demonstrating the things i need to demonstrate we're going to do some class properties class constants and some static properties also so let's start simple i'll just add a simple public name property i can use the same file to perform our logic so i'll new per calendar i'm going to assign a value to the calendar name and then all i'm going to do is print that out so a nice easy one to get started i'm going to stick a new line on the end so it renders cleanly in the terminal over to the terminal php calendar.php and there you go okay so in addition to class properties we can also have class constants so constants are owned by the class and not the objects and obviously their value remains constant and we define them like this and we access them like this so we use the class name double colon and then the constant name and i'm putting the line break on the end so this is called a scope resolution operator or double colon and as you can see we're accessing it off the clasp and not the object like we did for the name so let's go over to the terminal and the value is 12. now to access constants within the class we use the self keyword followed by the double colon so i'm just creating a public method here to demonstrate and again using the double colon so self double column followed by the constant and we'll go down the bottom and we'll just um call that method off of the calendar which we created so calendar get months and year and line break up to the terminal run the file and the exact same result as when we called it directly off the class so i'm going to revert back to where we called it directly off the class just like you can with normal properties you can also give constants visibility so i've changed this to private off to the terminal and as you can see we're getting an error because we're trying to access a private constant and of course we get the error because we're trying to access it outside of the class you can only access private properties and constants within the class so here's the rules regular properties they belong to the objects and their values can vary between objects constants value remains constant and it's associated with the class sort of in between the two we have static properties whose values can change but the value remains the same for all instances of that class so i'll give you a demonstration here's how we actually define them we use the static keyword so i say public static and i'm going to demonstrate this using the number of days in february which i'll set a default of 28 and first off we'll just print that out so i'm accessing it using the class and the double colon and you'll also notice that we didn't drop the dollar sign like we did with normal properties the dollar sign remains over to the terminal to inspect and we get 28 which is what we used as a default now watch what i do here i'm going to increment the value using the class and then using the object that we created i'm going to access the value so what do you think we will see here back to the terminal and it prints 28 and 29 so 28 is this first line here it's what we initially defined then we incremented the value and then printed it again except this time accessing it from the object so we use static properties when we have a value which we want to remain the same for all instances of that class and so here i'll show you practical usage because quite often what you want to do is count objects which have been instantiated from that class so here i'm using the constructor to increment a static count property by saying self double colon count and then increment using plus plus so print out the count and as you can see we'll get one because we've only instantiated one calendar object let's create a new one so we'll call it calendar two so this time our count is two because every time a calendar is created then the construct method is called behind the scenes and the count is incremented that's an introduction to static properties now what i'll do is i'll show you some of the things which are and are not allowed when you're defining these pros class properties so here's an array the value for this array is constant it's nothing needs to be evaluated we're going to get back spring summer autumn winter so this is allowed and i'll just demonstrate that in the terminal there we go spring summer autumn winter however you can't have something which is the result of an expression so i can't like use a function to merge two arrays together and say give me the result of that this isn't allowed because php has to work this out at runtime it's not something which is this isn't something which could be compiled and stored and given an address in memory so as you can see there constant expression contains invalid operations now some things are allowed such as basic mathematics so i'll demonstrate using number of weeks in the year so i'll take 365 as the days and year and i'll divide that by seven so that should give me the number of weeks in that in the year containing 365 days let's check that out in the terminal so 52.14 blah blah blah so you might be thinking well why not just call it 52.14 and that's a very good question but the only thing i can think of is it might just make more sense to do this and then you can show other developers how you've actually arrived at this bizarre number 52.14 let's have a look at something else which is also allowed so you can have predefined constants so i'm going outside of the class here and i'm defining a year constant as the number 2021 and so inside of the class i'm going to set the year a year property to the year constant let's print this out just to show you that i'm not making this up and i'll also append a new line and then let's go over to the terminal and there you go 2021 just as we expected what should we have a look at next okay here's something which has been around in other object oriented uh programming languages for a while which is fairly new in php and that is typed properties so as you can see here i'm stating that the name property should be a string weeks in the year should be a float and year should be an integer so with that in place what would happen if i tried and set weeks in the year to the string 52 let's print that out and see what we get back in the terminal and we have an error uncaught type error type property candle weeks and year must be a float but string was used so it gives us some protection so i'll change this back to a float to make it work one thing i like about this is it does a check for you so you don't have to write in if conditionals to make sure that you're getting the right kind of value it does it for you how about if i set weeks and year to be null now as you can see i got a squiggly line which kind of gives it away it's not allowed if you give something a type such as a float you can't actually initialize it as null however you can put a question mark in front of it like i've done here and then that will accept both the type as in float or it'll also accept null so if i do initialize it as null like i have done there then it will accept that perfectly fine no problem i'll change it back to a float to demonstrate that it will take either or so 365 divided by seven so it's telling you it's a flow it will accept null or float if you use the question mark in front of the type name okay here's a list of types which are allowed boolean integer float string array object iterable self parent class or interface name and as you can see at the bottom we have question mark and type and if you read the description it tells you that the property must be the specified type or null in this recording i'm going to cover magic methods magic methods are a special kind of class method which you don't call yourself but which are called behind the scenes by php when you get your objects to perform specific functions i'm going to use a connection example as in digital conferencing connection such as zoom skype etc and that will give us a good opportunity to show you what magic methods are and how and when you can use them i'll start by creating a new file called connection.php and this is going to hold my connection class so only in php tags and class is connection so here's the list of um magic methods about 15 of them the good news is we've already been using the most famous one of all construct up until this point i want to keep count of my connections so the way i'm going to do that is using a private static property called count and then i'm going to add my constructor and inside that constructor every time this is called it's going to increment the count property and the construct method will be called behind the scenes whenever we create a new connection object so let's create a file where we can go and test this out i've called this magic methods.php just kick off some html there opening and closing php tag and i'm going to require the connection php file and so what i want to do is just new up a new connection with connection one equals new connection construct should get called and our account should be incremented all behind the scenes let's put a line in here where we can echo something out and get some feedback and see if this has worked and we're just going to say what the current number of connections is now our account property is private so we can't just access it we're going to need to do a bit of work before it can do that so quick challenge for you if you're up to it using this class create solution for accessing the account property in magic methods and then display the value in magic methods dot php here's my solution have a go at it if you fancy it public function get count and all we're going to do is just return self count simple as that i'll grab this comment and i'll cut it and i'll copy it over to my magic methods file just so we're keeping track of what we're doing and all we have to do is just depend on the end of this connection one and then instead of trying to access count statically what we're going to do is we're just going to access the getcount method and i'm looking to append magicmethods.php okay so far so good number of connections is one that's what we expected just to prove that this is working let's add a second connection refresh number of connections is two let's now unset a connection and see what happens hmm that's not good the number of connections is still two even though we've got rid of one let's double check to make sure it's really gone so use print r which allows you to view variables in a human readable format over to browser yep it's definitely gone undefined variable so that's definitely gone we can no longer reference that but our number of connections is still two so we have a problem but it's an easily solved problem so like we have the constructor we also have a destructor which is simply this underscore underscore destruct and destruct is called as soon as there are no other references to a particular object so we unset it and when we unset it if we have a destructor then that destructor will be called behind the scenes when that action is performed so i'll let you have a go at this how do you suppose we will reduce the count when that object is unset have a go you should be i'll get this one just take a glance at the constructor if you need a little clue here's my solution so self double colon count and then negative negative to decrease the count by one let's go over to the browser give it a refresh and there you go now the number of connections is one that works perfect i'll comment it and uncomment it just to double check always double check your work so uncomment there we go yep that's definitely working the way we want it to okay you ready for a new one let's try get so this will be underscore underscore get and it's the magic getter we'll use a connection id which will be a string for this example and if you recall from the properties uh recording we could add dot blocks and we'll just put in a bit of an explanation as to what this is for other developers so it's a string and it is the connection identifier and it's a just a private regular property this one isn't static let's create a setter for that property so we'll just call this public function set connection id and so to give this a sense of realism what we'll do is we'll pass in an ip address and concatenate that with account and we'll call that the connection id so this connection id equals ip address underscore self count now the ip address this might be something that you want to protect because at the moment someone could just pass in anything and that would be accepted so what we'll do is we'll perform a check first and we'll validate that it is a valid id address and if so we'll set the connection id so we can do that using a function called filter for not sure if you've seen it before and what that does is it takes a value and performs a specific kind of validation on it and what we're performing on this is filter validate ip and that will validate that it's a legitimate ip address if that condition isn't me and the ip address fails we're just going to say die and we'll put our string not an ip address when we get onto exceptions we'll put in some better error handling okay so it's a private property so we're going to need some way to access it now what we've learned up to now is to use getters like so get connection id which is perfectly valid and this is the most common way of doing this however what i'm going to show you with the magic getters is an alternative way of accessing this because say for example here is where you might want to use it what if you have a growing list of private and protected properties and you might even have dynamic properties which you're adding to the class on the fly which is something we'll look at later it won't be practical to have a getter for each one okay we have the setter here because we need it for that protection when we're setting the value but there's actually an easier way of or a more efficient way of accessing those properties so in order to demonstrate this i'll add a second private property for the conference id and what we use is something called the magic getter which is underscore underscore get this method will get called behind the scenes when we try to access private or protected properties like say use foreign data from in accessible ie protected or private properties and the way that we most typically use it is this we just say return this and the name of the property that we're trying to access so let me try and explain that a little bit better in the example we're going to use we're going to try and access connection id of an object connection id is what will get passed into the magic get method so that's what we're going to access in effect what we're going to be doing is this when we try and access connection id you'll call this magicgame method and it's just doing this basically under the hud and so now we can access connection id conference id whatever we don't need to create getters for each of our public and protected and private properties so don't just take my word for it let's go and give this a go so we'll set a connection id i'll just check so that works first let's set it to something which is legal not a valid ip address okay that's working well now let's print these values out to the browser just to prove that it really is working so as you can see here i'm accessing the conference id as if it was a public property doing the exact same thing with a connection id which i shouldn't be able to do because it's a public property but we've created our getter so it should work over to browser refresh we see our conference id and we see our connection id to finish off we'll use the magic tostring method so at the moment if i wanted to echo out my object or treat it as a string printed out like this i'm going to get an error encore error object of class connection could not be converted to a string so the magic to string method actually allows you to represent your object as a string so when i say print connection 1 it will print a string which i have built in the tostring method of the connection class let me show you exactly how this works underscore underscore uh two string using camel case and like i say it returns a string representation of the object so like it says here the class decides how it will react when it's treated like a string so the one big essential requirement here is that we actually return a string let's document that using our dot blocks and the way we document it is we say at return string so you're telling anyone who reads this code you must return a string from this method and we'll just build up a string um conference id call on conference id and then we'll put in a line break and then conference uh connection id is this connection id so this is quite a typical use of the two string method you'd return a string which contains some of the data or some of the information regarding the object and we're just printing that out here conference id one two three four connection id is ip address appended with the count so let's recap we've covered construct which you already knew about destruct which is called when the object no longer exists get for accessing inaccessible properties such as protected and private properties and we finished off with tostring which allows the class to decide how it will react when it's treated like a string and we just returned some of the classes data so i hope you found that useful here's the full list there's roughly 15 of them we've just covered some of the basic ones for now but we'll definitely be looking at some of those in the future i think for the time being it was just good to introduce them to you let you know what they are how they work and what makes them unique in this one i'm going to cover abstract classes so i'll show you what they are why and how we use them and then i'll demonstrate using a fairly common example which is that of representing database tables with objects it's a technique which is common to all major php frameworks such as laravel and symphony and we will come on to covering that stuff later in the course so here's my database admin tool as you can see i've created a database with a couple of tables products and users i'm going to create classes which represent each of these tables and those classes are going to inherit from an abstract parent class so for lack of a better name we're going to call this abstract class data model now an abstract class is one which will never instantiate there will never be an instance of a data model class and it would be meaningless anyway because we don't have a table in the database called data model we need to extend this with our concrete classes that's what we refer to as the classes which we instantiate and the abstract parent provides properties and functionality which is shared amongst the child classes okay so enough jibber jabber let's get into this i'll start off by creating the data model class so as you'll see we create it in pretty much the same way we use the class keyword except in front of that we also add the abstract keyword adding the abstract keyword will now mean that php will not allow me to create an instance of a date model class we're going to need some properties and methods in order to give this a sense of realism i'm not actually going to really connect to a database because there's quite a lot of setup involved in that and i don't really want to get sidetracked i just want to explain the concept so i'm giving this a property of table name and i'm just going to give it a default random table name value also a save method which is quite common for this kind of class and i'm just pretending that i'm saving something to the database this is just a placeholder string to give an idea of what this method should actually do in real life now let's create a file where i can go and play with this stuff and demonstrate it in the browser so in the same folder i'm just going to create a file called abstract classes dot php i'll just remove this opening php tag replace with a bit html i'll give the file a title abstract classes and then within the html body i just add my opening and closing php tags i need to require the data model file so require datamodel.php and i'm going to try and instantiate an instance of the data model class one of the good things about ids like phpstorm is they tend to tell you if something's not going to be possible as you can see here and it gives me a message in the bottom corner cannot instantiate abstract class data model i'm still going to give it a go because that's the kind of reckless maverick that i am and i'm going to try and call the save method on it as well so over to the browser and it's telling us we can't instantiate abstract class data model the reason why we can't instantiate it is because it's abstract and abstract classes aren't supposed to be instantiated they're supposed to be extended so let's do that now so over to the database again as you can see we have this products table with a couple of properties name and price let's create a product class in the same folder so class product extends and we're going to extend it data model so it'll inherit the public and protected properties and methods from the data model and i'm going to add a couple of private properties of my own which are the name and also the price and you'll notice that i've also given them property types of string and float it's good to get in habit of using stuff as and when you learn it okay i'm now going to create some getters and setters for each of these properties again for a class like this an entity class or model class whichever you want to call it this is also quite typical you'd set your properties and then you'd call the save method to persist it to the database if you're wondering what these things are here i apologize not cover them yet these are typings and they're basically telling php what kind of values or what type of values to expect that's stuff that we are going to cover and it is coming up shortly okay let's round off this class by requiring once our datamodel.php file and then what i want to do is go over to my abstractclasses.php file i'm just going to change all the references to data model i'll delete this so i'm requiring product.php i'm newing up a product with product equals new product and then same as i've tried for the data model i'm going to call the save method so let's go over to browser and give that a go refresh okay our error is gone that's good and it's saying saving data to table name random table name so it would be better if we actually create our own table name property in the product class by doing that when you recreate the same properties and methods in child classes it's the ones in the child classes which are referenced and we call this technique overriding okay so back to the browser gives a refresh saving data to table products hopefully now you've got a grasp of how that works do you want to give it a go yourself i've written some instructions here so here's what you need to do first create a user class to extend the data model class then on that class set the table name over in abstract classes.php new up a user and call the save method and then just go to browser and check your work okay give it a go hopefully you should find it fairly straightforward here's my solution except i'm not going to include the getters and setters this time that was just to illustrate how these kind of classes are used so i'm requiring once the data model in my new user class and then i'll just set a table name to users so protected string table name equals users what i need to do then is go over to the abstractclasses.php change the references to product as to user rename these just for continuity refresh and there you go saving data to table users in this recording i'm going to look at abstract methods i'll show you what they are how we use them and where you'll use them and for a bit of a change i'm going to demonstrate using some mathematics and some geometry i'll start things off in the chapter 3 folder by creating a new class and this is going to be an abstract class and it's called three dimensional shape and this is purposefully designed to be extended by concrete implementations and the examples i'm going to use in this recording are a cylinder and a sphere so you want to instantiate a three-dimensional shape class because it means nothing but you would instantiate a child class a more concrete version such as the sphere and the cylinder now i'm adding a volume method here and this is a method for calculating volume so if you think about the different shapes that we're going to use the calculation is going to be different for each one and because calculation is going to be different for each one i can't put the code in this three-dimensional shape parent but what i can do is make the function abstract and that means that each child of three-dimensional shape must implement a volume method and you'll notice i'm removing the body here we only define the name visibility and params for abstract methods the bodies are needed because this is a contract which is saying if you extend this class you must implement this method so let's do that now in the chapter three folder i've created a class called cylinder and that extends three dimensional shape the red squiggly line is php storm telling me that i must implement a volume method in this class and it's in this method that i'll define the body and one thing to know is that the signature ie the parameters and return type must match those of the abstract method in the parrot so let's go over to google and find out how to calculate the volume of a cylinder so it can be pi multiplied by radius squared multiplied by height that's a good candidate for a dot block so you can explain to the developers how you're calculating this php has built in functions which will help us with pi and radius squared the dimensions is going to be an associative array because um it's going to be different for each kind of shape so i think an array is probably the easiest way to do this so it'll have a radius key and it will also need a height key so pi multiplied by dimensions radius squared multiplied by dimensions height let's require once our three dimensional shape dot php file and then we're going to need a file where we can go and test this out so i'm creating a just a standard php file called abstract methods in the same chapter 3 folder a bit of html change the title to abstract methods and then i need to require the cylinder dot php file and i'm going to create a new cylinder cylinder equals new cylinder and i'm thinking we can actually improve our design here by passing in the dimensions to the constructor when you make this kind of improvement it's called refactoring so we're not going to change how the code behaves we're just going to make it more logical i'm going to do that by putting a construct method in the three-dimensional shape abstract class that will take the dimensions array and then we'll create a dimensions property on the class and so in our methods instead of passing in the dimensions array we'll just be able to say this dimensions and this will make you mandatory to pass the dimensions array whenever you create a new shape or three-dimensional shape of any kind so we can remove the dimensions argument from the methods in the calculation itself i'm replacing the dimensions variable with the dimensions property and i'll do that for both radius and height and then also in the dot block i'll remove this param here and let's go and pass in an array to our constructor so i'll say radius equals 5 and for the height i'll call that 10. so i think it makes quite good sense to pass in these dimensions when we create the object itself let's now calculate the volume and all we need to do is just call cylinder volume now what i'm going to do is print it out using print underscore r and i'll just go over to the browser and see what we get so i'll pin the file name onto the end of the url and that doesn't look right what we're doing there let's go back to the file yep need to say php okay back over to the browser refresh okay we have a number 785.398 blah blah blah i've no idea if that's right but i know someone who does i'll put my dimensions into this google helper here and hopefully i'll get a similar number seven eight five point four that's obviously been rounded but it's good enough for me seven eight five point three nine okay so your chance to have a goal should you accept the challenge here are the steps create a sphere class to extend the three-dimensional shape abstract class add the mandatory volume method to calculate the volume of a sphere and return that value add a new sphere object to the abstractmethods.php file and call the volume method on it and then all you need to do is print out the result in the browser so here's how you do it have a go at it class sphere extends three-dimensional shape and i've got that squiggly line because it's mandatory to implement this volume method and so i need to figure out how to calculate the volume of a sphere so over to google and google tells me that it's 4 divided by 3 multiplied by pi multiplied by the radius cubed so let's add that to our volume method return 4 divided by 3 multiplied by pi and then you multiply that by radius to the power three which we can do using this power function and under dimensions property we will have an array which contains a radius key so we assign the dimensions property in the three-dimensional shape constructor and when we create a sphere we'll just need to remember that we'll need a radius key for the array in my sphere file i've required the three dimensional shape dot php file now in the abstract methods file i require sphere.php and i need to create a new sphere and it's in the constructor where i set this radius and we'll stick with five and then all i need to do is call the volume method on sphere so sphere volume equals sphere volume and i just have to print that out and then go and check my work in the browser so we'll go over there now and we'll get 523.59 let's go and check this with google's calculator and see if that will give us the same value put five in there okay five two three point six that's close enough so i'm going to finish off with a couple of things one of those will be tie printing where we tell php what type of value to expect and i want to demonstrate something else to you as well so as you can see our number of dimensions varies for each of these shapes for certain types of shapes such as cubes cuboids the number of dimensions will be fixed ie length height width so i'm going to introduce an extra level of inheritance so my sphere my cylinder will now inherit from a non-cuboid shape class which inherits from the three-dimensional shape and the reason that i'm doing this is to show you in what circumstances you can be exempt from having to implement the abstract methods now it's non-cuboid shape much like it's apparent three-dimensional shape it's not something that you would instantiate it's an abstract notional class so i'm gonna make this abstract and in doing that it means that the non-cuboid shape does not need to implement the volume method that responsibility will get passed down the chain to the child classes of the non-cuboid shape so i'll require once the three dimensional shape dot php file go over to cylinder i'm going to change this so it extends non-cuboid shape i'll change my require over to sphere do exactly the same thing sphere extends non-cuboid shape need to change the require once to non-cuboid shape also and so let's go and run the code nothing breaks exactly the same behavior that was the sphere we need to check the cylinder volume also so i'll move that up there change that to cylinder excellent so that's passing it as well no changing behavior nothing breaks so let me just clarify that rule if a class extends the three-dimensional shape then it must either implement the volume method or also declare itself abstract okay type ins so this is a type hinted argument this is a type hinted return when i type into array in my method signature like this what it's saying is that whatever gets passed in must be an array so i'm going to change this to an integer and then i'll go and run this in the browser and see what happens so there you go argument one past three dimensional shape construct must be of type array integer given so that's pretty good it's another thing which protects our application and it means that we don't have to do checks to ensure we're getting past the right values because php is doing it for us so i'll return this to how it was and we'll go and have a look at the other one which was type hinted returns so over in our sphere class we said that the volume method must return a float let's comment that out and return a string any string will do i think the value was five point something if i can remember rightly so i'll just return a string five-ish over to the browser refresh okay return value of sphere volume must be of the type float and the string was returned in this recording i'm going to look at interfaces in object-oriented php i'll look at what they are how you create them and where you will use them and i'll demonstrate using a client for contacting third-party apis so let's start off with the questions what are interfaces and how do you create them so code along with me and i'll explain as we go along i'm creating an interface here and it's going to be called weather api client interface so it's just like creating a class except i swapped this class keyword for the interface keyword and just like that you've created your first interface and an interface is like a contract you don't extend it like you do with classes instead you implement it and when you do implement it you're saying that you're going to adhere to it you're going to implement the methods which it defines so fairly similar to abstract classes and methods in that respect and also similar in that i don't define the body of the methods that is done in the classes which implement the interface so i've created a weather api client interface here and i'll now create concrete classes which implement this interface the example i'm using for this recording is a client for contacting a third-party api so i'm going to look at a couple of third-party apis which have a which are weather based apis i want to get the same or similar data back from both of them but obviously they're both different apis and they're going to behave differently this first api is called dark sky and it requires me to pass latitude and longitude coordinates the second one is called open weather map and instead this one requires a city name so even though these two apis work differently my two clients are going to appear like they both work the same by implementing a comment interface and hiding away the different functionality behind the scenes as you can see i got this squiggly angry red line and that is because i need to add a get forecast method when i implement the weather api interface not only that but it must have the same signature i.e it must take a city as a parameter next over to the dark sky api client and here i'm going to implement the same interface so dark sky api client implements weather api client interface again i have to create the method get forecast and i also have to add city as a parameter so no matter whether using dark sky api client or the open weather map api client the way that the rest of your code interacts with these two clients will be exactly the same because they both implement a common interface let's figure out how we can make this work so the dark sky api like we said it needs latitude and longitude coordinates so the first step we can do is get the latitude and longitude of the city that we're passing in and then we can call the dark sky api using those latitude and longitude coordinates now i'm not going to physically write the code to get the latitude and longitude of the city or call the api i'm just demonstrating how you would go about normalizing that behavior so that on the surface you have something which appears to work the same way for both dark sky and open weather map for the open weather map client there's one step less because that uses a city anyway so let's require once our weather api client interface file and we need to do the same for the dark sky api client so i'll require once whether api client interface and then let's create a file where we can go and play around with this stuff and display stuff in the browser so i'll call the interfaces.php i'll change the title to interfaces opening and closing php tags and it will start the dark sky api client so require dark sky api client and then i'm just going to create a new dark sky api client but i'm going to call it weather api client because it's less specific it's more abstract and it's a much more suitable name should things change as you will see shortly so we'll get a forecast back from the weather api or in our case we'll pretend to get a forecast back from the weather api i'll give this a sense of semi-realism by adding a weather app heading and then i'm just going to echo out that forecast to the browser and then all i need to do is go over to the browser itself and the address is localhost followed by my port and then interfaces.php and that's just echoing out it is raining in followed by whatever city name i gave it so let's imagine that we've been using our dark sky api client for a while and then all of a sudden it becomes unavailable or for whatever reason we can't use anymore we're going to need to find an alternative now if we've been good developers and we've implemented interfaces it will make life a lot simpler than if we hadn't all of our code which performs the action of getting a forecast can stay exactly the same as long as our new client implements the getforecast method it means all we need to do is just swap out the old class for the new one and on the surface when we refresh exactly the same but behind the scenes the open weather map client when the get forecast method is called that will go and do what that needs to do in order to get the forecast so we could have multiple parts of our application which called the weather api client or just different parts of our application which rely on others if you've coded to interfaces and contracts it will make life a lot easier for you when things need to change so that's been an introduction to interfaces what they are and how you create them in the next one which is polymorphism i'll show you just how powerful they really can be when you inject them into methods in this recording i'm going to cover another one of the object-oriented programming fundamentals polymorphism polymorphic objects are the shape-shifting superheroes of object-oriented programming they are objects which can take on many forms and as you'll find out as i will demonstrate to you they're both powerful and flexible so here's what we're going to do i have a couple of files which are inventory files one is in csv format as you can see here it has a header and then three rows of data and here i have an inventory file in json format which contains the exact same data but it's just in a different format i'm going to build a mini application which is able to read either of those files in either format and take the content and return me this an associative array in this exact format so no matter whether it reads the csv or the json it will return me this array in this format my code should be able to handle either scenario seamlessly and without making any adjustments because it will be polymorphic before i get into a full-blown explanation of polymorphism we're just going to build out some of this application so code along with me i've created a class called csv file reader and that will implement a interface called file reader interface so let's go and create that file reader interface and so as you can see instead of the keyword class it uses the keyword interface this is going to act as our contract so the classes which we create for reading the data files will implement this file reader interface and there'll be one method which they must implement and we're defining that here read file as associative array it'll take the file name as a argument and it will return that associative array which i showed you earlier on so if i look at my csv file reader now phpstorm is shouting at me because i must implement that method a lot of the time what i'll do before i start writing any code is i'll just add comments and sketch out the steps that i need to take in order to make this work so i'm going to crop the rows from the file as arrays i know i can do that with some of php's built-in csv handling functionality i'll separate the header and then each part of the header will be a key which maps to a value so this is how i'm going to do it i'm going to use array map this takes two arguments the first one being a callback function and the second one being an array so the callback function i'll use php's inbuilt str underscore getcsv the second part here converts the file contents to an array each line of that file will be an array element so in our case each one of those elements is going to be a string with commas in it and what happens is array map will loop through each of those lines pass the line into the str get csv function which will split it into an array at the commas we'll end up with an array containing four arrays the first one will be the header and i'm splitting that out here using array shift then we need to somehow get the header elements or the header keys and match them up with the values and we're going to do that like this so we'll loop through each of the rows as you can see i've established an empty items array and what we're going to do is loop through each of the rows and then we're going to kind of zip the elements in the header and the row up together so that they're matching and we do that using this built-in php method called array combine we'll pass the header in as the first argument and then the row as the second so each element in the header one two three will match up with each element in the row one two three we add our newly combined array to the items array and then all we need to do is return it and that believe it or not should return as array in the exact uh our content in the exact same array format as what we specified so i'm going to require once the file reader interface and we'll try this out so i'm just going to stay in the same file outside of the class obviously outside of the class curly braces so file reader equals new csv file reader and then i'm just going to call the method read file as associative array and it's the inventory.csv file that i'm reading i'll store that in an items array and i'll just print that out using print underscore r function add a php end of line which is more of a habit than anything else and then i just need to call this using php csv file reader and that looks exactly the same as the associative array that we said we were aiming for from the start so good progress we'll comment this out what i want to do now is create a class which is going to use the csv file reader and so i'm going to create something called stock manager and what this does or what it will appear to do is read a csv file of data and then update a database with the information from that file the main method in that class will be this one update stock from file it will take a file name as the first argument and for the second argument i am using a method called dependency injection to inject a csv file reader into the update stock from file method now csv file reader is now a dependency for this method and when you inject a class or when you pass a class in as an argument to a method you call it dependency injection i'm not get too deep into it right now but something like this csv file reader you refer to it as a service class because it performs a service for other classes and you're usually more likely to inject in through the constructor i'll park that there though and that's something we'll come back to another time for now we're doing it this way and as you can see i'm using the csv file reader read file associative array method i'm getting the return value of that and storing it in stock items which will be an array and i'm just going to loop through that and then i'm pretending that i'm adding a record to the database what i'm actually going to do is just print it out i'll require once the csv filereader.php file and then once i've done that i'm going to need a file where i can go and play around with this stuff and print stuff out to the browser so in the chapter three folder as usual i'm going to create a file called polymorphism.php add some html i'll rename the file title to polymorphism opening and closing php tags and so what do i need to do here i'll require once the stock manager file and then i'll create a new stock manager with stock manager equals new stock manager and then what i want to do is call our method the update stock from file so it takes two arguments which the first one being the file name and we're still using csv and then the second one we need a csv file reader so we'll also create one of those csv file reader equals new csv file reader and we required that in the stock manager file so this should work let's go over to the browser and take this for a test drive so localhost i'm using port 8000 and then it's polymorphism.php okay so the data looks good i'm not sure about the formatting so i've used a line break instead i'm just going to use a html uh break tag and there we go that's much better i'll just bump the size up on this a bit so it's easy to read and now we'll turn our attention to the json data so what we want to be able to do is also read the json inventory file and update the database using that but we can't really do it using what we've got currently because the csv file reader this is set up to handle csv only so we need another solution we're going to need a json file reader so let's create one of those and again i want this to be able to return me an array of data in exactly the same format as my csv file reader so i've called the file json file reader this is also going to implement the file reader interface so i'll require the file reader interface php file class json file reader implements file reader interface as you can see the squiggly red line is phpstorm telling me that i must implement the read file as associative array method and so exactly the same method name except the internals of it will work differently like the csv file reader i'm going to sketch out using comments doing this kind of thing is quite a good practice to get into because it just keeps you focused on the task in mind rather than trying to think as a code as you go along you end up writing a lot more code than what you need to that way i find so i'm going to use the file get contents method i'll pass in the file name and that will take the contents of my file and read it into a string so the file was in json format which means i'll end up with a json string and then in order to convert that to an associative array i can just use php's json decode method that will take the string as the first argument and if i pass true boolean as a second that will convert it to an associative array and then all we need to do is return that items array and it should return it in the exact same format as our csv file reader let's test that theory now and we'll stick in the same file like we did with the csv file reader just to test this out that's the code you need you're just creating the class calling the method let's go to the terminal and run this now so php json file reader and that looks exactly the same the same format the same data as what we got back from our csv file reader so this is interesting we now have two files the json file reader and the csv file reader which both have the same method names let's go back to our polymorphism file and we'll try and use the json file reader in our stock manager in the same way that we did with the csv file reader so json file reader equals new json file reader and instead of passing in the csv file reader i'm going to try and pass in the json file reader so you probably know by now that this isn't going to work but just go along with it for the time being i'll require the json file reader let's move over to the browser and give it a refresh fatal error on caught type error so argument two past the stock manager update stockman file must be an instance of csv file reader we've tried to pass in the json file reader so i did this deliberately really to illustrate what happens when you don't use polymorphers and when you use concrete dependencies let's have a look at the method so it's totally inflexible because we've injected csv file reader which means that we are stuck with only csv file reader or a child of a csv file reader and it eliminates all of the possibilities let's change that and make our code more flexible so as you can see here instead of injecting the csv file reader i'm injecting a file reader interface i'm going to change all references to the name csv file reader to file reader which is more abstract and as you recall both the json file reader and the csv file reader both implement this interface so you might be thinking where does polymorphism come into this so thanks for your patience let's cover a bit of theory now i'm going to knock up an interface file or a file where i can play around and create classes so i'll create an interface called random interface and i'm going to create a couple of classes class a and i'm just going to leave them as empty classes for the time being class b and i'm going to make class b extend class a so in php there is a way of checking if something is an instance of another class or if an object is regarded to be an instance of a particular class i'll instantiate two objects here one for class a and one for class b and i'm just going to write a little conditional and using the instance of which checks if something's an instance of a particular class i'm just going to check various scenarios the first one is fairly straightforward i'm checking if object a is an instance of class a so i think we both know what the answer to this one will be but we'll go and run it in the terminal anyway so random interface and it's true object a is an instance of class a let's try another one as you can see class b extends class a so what do you think will be the outcome if we check this one is class b an instance of a o to the terminal and it's true okay so let's now check if object a is an instance of random interface false let's make class a implement random interface so class a implements random interface what do you think true so this is getting interesting if you think of the example we've been using we've got a lot of power here how about if we check if b is an instance of random interface so b is a child of a a implements random interface what do you think that's also true polymorphism is the ability of an object to take on many forms so in php an object that can pass more than one instance of test is considered to be polymorphic so keep a note of that definition because you'll definitely be asked it in an interview at some point let's change this require once so we're now requiring the file reader interface and we'll go over to our polymorphism file and we'll demonstrate that our code is polymorphic so the first one we're going to check is we'll just leave it as it is with the csv file reader being injected refresh that works we'll also prove that the update stock from file file reader object can be a json file reader so stock manager update stock from file we're reading the inventory json file and we're going to use the json file reader this time over to browser refresh it works for both because the file reader object is able to take on many forms so there might be parts you code where you want to read csv files it might be parts you code where you want to read json files we're now equipped to be able to do either of those things our code's nice and loose the file reader just has to implement the file reader interface and that permits us to inject it into here and then the underlying mechanism of how the file is read will change dependent on whether you're using json file reader csv file reader this recording was about polymorphism but we've touched on some dependency injection there don't worry about understanding everything because we'll be covering dependency injection in a lot more detail later on in the course you
Info
Channel: Gary Clarke
Views: 2,735
Rating: 5 out of 5
Keywords: object oriented php, php tutorial, php oop, PHP OOP Beginner to Professional, Object Oriented PHP Tutorial For Beginners, learn oop php step by step, php programming tutorial for beginners, creating objects in php, object oriented php with real examples, learn object oriented programming php, Learn Object Oriented PHP 2021, php objects, learn object oriented programming, php object, oop php interview questions, learn php 2021, learn php for beginners, php full course
Id: NyRWaQo1pZo
Channel Id: undefined
Length: 124min 12sec (7452 seconds)
Published: Tue Jun 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.