PHP Classes & Objects - Typed Properties - Constructors & Destructors - Full PHP 8 Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's talk about classes and objects a class as mentioned in the previous lesson is like a blueprint and an object is something that you build from that blueprint or in other words an instance of that class object is a php data type that we haven't covered yet in the first section of the course we covered four scalar types we covered arrays callables resources and null data types that leaves us with two data types that we haven't covered yet and that is iterables and objects iterables will be covered later in the course and today we'll talk about object data type php has a generic class implementation called std class that you could use to create generic objects or you could cast your variables that are off and other data types into objects and we'll talk about that towards the end of this lesson so make sure to watch it till the end in addition to being able to create objects using generic std class you can also create your own custom classes let's create a class called transaction because it applies to the project that we'll be working on the definition must begin with a class keyword followed by the class name which should begin either with a letter or an underscore followed by letters numbers or underscores so in this case that's just transaction and then we put curly braces to enclose the class definition note here that you could follow different standards and conventions when it comes to naming your variables or classes or overall your code structure you don't have to name your classes after your file but that is the recommended and widely used convention you could also have more than one class definitions in a file which would work perfectly fine but again it is not the recommended way the recommended way is to have a single class per file and nothing else in that file we'll cover the psr standards and conventions in this course so don't worry about it now so now that we have a class let's create an object as i mentioned before you could also create the object within the same class right after the closing curly brace but i'm not going to do that because it is not the recommended way so i'm going to create the object within the index.php in public directory so i'm going to call my variable transaction and to create an object we need to use the new keyword followed by the class name which is transaction followed by parentheses and parenthesis is not always required depending on your constructor but it's always a good idea to stay consistent and just use parentheses regardless so let's bar dump transaction and let's open it in the browser and we get fatal error that's because index.php does not know where the transaction class exists it hasn't loaded that file we need to explicitly include or require this file for index.php to be able to create objects of transaction class later in the course we're going to cover something called namespaces and autoloading where you will not have to do that but for now we need to require this so i'm going to add require once and the transaction class is in the parent directory so dot transaction.php and if i refresh the page now it prints an empty object we see that the data type is object and its instance of a transaction class a class can have variables which are called properties and functions which are called methods so let's add couple of properties to our transaction class a transaction at minimum should have an amount and description properties right so let's add those two properties we need to define the visibility of the property to either public private or protected and these are also called access modifiers and they should be added to both properties and methods so we start with the access modifier in this case let's do public then the variable name so that is amount and semicolon and we do the same thing for description and now we have two properties that are publicly accessible if we refresh the page we see that amount and description are available there and they're set to no the values of these properties will be set to no if you don't assign them the value so the null will be the default value for them now there is one exception to this when using type hinting and we'll get to that in a minute as mentioned before public means that it's accessible to everyone interacting with the object even outside of the class so if we wanted to var dump the value of amount all we have to do is use the object operator which is dash greater than sign and as you can see my id autocomplete showing me all the publicly available methods and properties in this case we only have two properties and no methods so we're going to use amount and we've already done that and we get no because it has no value if we change the access modifier from public to private and refresh the page we're going to get the error what private means is that this property is only available and accessible within the class itself and the third access modifier which is protected we're going to get into that once we get to the inheritance topic so don't worry about it for now let's change this back to public refresh the page everything still works when properties are publicly available you're able to change their values so right here we could say transaction amount equals to 15 and if we refresh the page now when we access it it's set to 15. php 7.4 introduced typed properties which means that you could set the type of the property in the definition so right here as you can see my id is underlining these two properties letting me know that i should tie paint them and tie painting is recommended but not required it is up to you if you want to use it or not i personally prefer type hinting and strict types so you will see me tie painting everything and using strict types in most of my code so i'm going to type in this float and i'm going to type hint this string and i'm going to declare streak types equals 1. now if we refresh the page everything will still work and we see that the 15 that we assigned is set to float now what do you think would happen if we remove this assignment from here and try to var dump the property that hasn't been assigned a value yet before when we had no type definition we were getting no however with the type definition if we refresh the page you're not going to get null you're going to get a fatal layer stating that the property should not be accessed before initialization now you might say that without type definition the default value of property should be no right because when we didn't define the type we were getting null as the default value so can't you simply make this nullable type by adding the question mark so something like this so if the amount gets assigned the default value null then you could say that this property is floating data type but it could also be no then do you think this would work the answer is no if i refresh the page you will still get the fatal error that's because php is not able to determine whether a property that has a type was actually set or you simply forgot to set the value this is why the new state was introduced called uninitialized when type is defined and value is not assigned to a property it is in uninitialized state and let me show you that i'm going to remove this question mark from here and let's var dump the class without accessing the property if we refresh the page we see that amount is set to uninitialized float data type and description is set to an initialized string data type if we remove the type from the definition here we refresh description is set to no amount is set to uninitialized so to solve the issue of accessing properties before initialization is to actually assign some kind of value either directly in the definition or in something called constructor or a setter that we're going to talk about in a minute as i just mentioned you're able to set the default value directly in the definition so you could say equals to 15 for example and now if we try to access amount this will work something to note here is that you're only able to assign constant values as the default values you cannot have complex expressions here like function calls and so on if you wanted to have the nullable property then you would add the question mark in front of the type definition and it would set the default value to no in that case it would work but this kind of assignment doesn't really make sense for this class because we're kind of hard coding the amount to value 15. when we're creating multiple transaction objects they're not all going to have the amount 15 right they will have different amounts so this is not the proper way though there are many use cases where you would want to set the default in the definition but in this case we'll use something called constructor to initialize our properties the constructor method is a special function also known as a magic method that will be called whenever a new instance of the class is created it starts with a double underscore and if i type double underscore my id will autocomplete all the available magic methods that php offers and the one that we need is the construct it's just like a regular method the difference is that this will get called every time a new object is created it can accept arguments here so we could accept float amount and we could accept string description and now we could assign these values to the properties to access the properties of the object or the class within the class itself we need to use a variable called this and this variable refers to the calling object or in other words it refers to the instance from which the method was called so we can say this amount equals to amount and this description equals the description now if you refresh the page we're going to get a fail error because we haven't passed any arguments to our constructor remember these parentheses that i mentioned before this is where you would pass the arguments so we can say 15 and transaction 1 as the description and if we refresh we get float 15. let's enable the strict types here as well and refresh the page everything still works and as you remember from my previous lesson about the data types and flow data type you are able to pass integer when floating data type is expected even when strict mode is enabled however if i change this to string now it's going to result in a fatal error let's create a method that will add the tax amount to the transaction amount as mentioned before methods should also have the access modifier similar to the properties as you can see the constructor method has the access modifier public by default and this is actually not required but it is highly recommended to always have the access modifiers on methods if i remove this by default php will assign public to all these methods that don't have the access modifier so if i refresh the page here it will still work though it is highly recommended to always set the access modifier to your methods to stay consistent and also it's better for readability so we'll bring the public back here and let's add a method called add tax which will accept the rate as an argument the way we calculate tax amount is by multiplying the transaction amount by the rate and then dividing by 100 and adding that amount to the original transaction amount so let's go here and let's add tax of say eight percent and let's change this to 100 and the final amount should be 108. if i refresh we get 108. let's create another method here to apply discount to the transaction amount so let's do public function apply discount flow rate and in this case we're going to subtract from the amount the discount amount and we'll calculate it the same way so amount times rate divided by 100 and let's apply discount of 10 and we refresh page that's 97.2 which is correct so as you can see this works as expected if i were to change this to private this will no longer work because this method is not accessible outside of the current class if i refresh we get that error so let's change this back to public and it works now let's also change the visibility of amount and description to private because it doesn't make sense to have amount publicly available that can cause some unnecessary bugs where the amount is explicitly changed outside of the class we should not let anything other than the transaction class itself change the amount property but instead to access the amount property we could simply create a getter function called getamount and that returns a float and let's return amount now in here we can simply do getamount and everything will still work and we'll talk more about the encapsulation and getters and setters in a separate video so one thing to note here is that i'm calling add tax and apply discount on the same object right so we're using this variable multiple times let's say we had another six methods that we had to call before getting amount so in addition to adding tax applying discount maybe you want to do some calculation you want to maybe add some additional amount or something like that maybe you want to call another six methods here instead of duplicating these lines and calling those functions that way you could actually chain methods by returning the current object from those methods so in this case add tags apply discount they don't return anything currently and we could simply just return this variable which refers to the calling object which is the instance of the transaction class and we could specify transaction as the return type there is another way to specify this by using the self keyword but we'll get into that later in the course once we get to the inheritance and statics so for now i'm going to use the class name and same goes for the apply discount we can return the transaction instance and return this and if we go back here everything still works but now we are able to do something like this where methods are changed if we refresh it still works and we could even do something like this put this in parenthesis remove this and this will still work and for better readability we can put this on a new line and put this on another line and put the other six methods that we would have on separate lines and this would still work even better we can set this to amount if we don't care to have the reference to that object and simply add get amount here and delete it from here and change this to amount and it will still work as you can see chaining methods creates this more readable way of building your objects i will talk more about this later in the course but note that chaining methods will not always make sense chaining methods would not make sense if we had to return a tax here something like instead of ad tax we had get taxed then training methods would not make sense because we need to return some type of value not the current instance also don't try to force yourself creating chained method structures in all of your classes it only makes sense for certain classes where as i mentioned before you want to kind of build up the object before getting the final value another way you could create objects is by using variables instead of the class name so in here we could simply call a variable like this and we could assign the variable class and you could call this variable whatever you want and set this to transaction like that and if you refresh everything still works so this allows you to create objects where the class name is stored in a variable so let's change that back and as i mentioned in the beginning of the lesson the class is the blueprint and an object is the instance of that class right and you could create multiple objects of the same class and we could do the same thing here we can create as many transactions as we want with different values let's call this transaction two for the amount of two hundred and we're going to apply eight percent tax and maybe fifteen percent discount and we don't need to get amount here and let's print transaction one amount and transaction to amount let's refresh the page and as you can see we have two separate transaction objects with two different values all right let's move on to destructors destructor like constructor is also a magic method and it needs to be defined with two underscores in the beginning so let's type two underscores and as mentioned before we see all the available magic methods here the destruct is the one that we need and the destruct method is called whenever there is no more reference available to the object or when the object is destroyed so let's print destruct and the description of the transaction with the break line and let's keep a single transaction here and let's do get amount so that i can show you two cases so that's the amount and let's print amount we refresh and as you can see you will first call the destruct and then print the amount what this means is that there is actually no reference available to this transaction aside from here and therefore it's calling the destruct and it's printing this drug transaction 1 and then we're printing the amount if we change this to transaction object and remove the get amount now we still have the reference available to it so if we try to get amount here it's going to print the amount first and then call the destruct method now what if we did something like this amount equals transaction get amount and we printed amount what do you think will happen do you think the destruct will be called first or the amount will be printed first the answer is that amount will be printed first and then the destructor will call the reason for that is because we still have the reference of the object available because even though we are assigning the value here this reference still is available until the end of the script when the script ends that's when the destructor is called and that is why it first prints the amount and then it calls the destruct while in previously when we called getamount here there was actually no reference available anywhere to that transaction object that's why the destruct was called first and then the amount was printed you're able to destroy your object by calling onset function or setting the value of that object to know so for example if we set unset transaction here this will call the destructor so if we refresh the destructor will be called first and then the amount if we set the transaction to null the same thing will happen it will call the destructor first and then the amount destructors can be used to perform some sort of cleanup or release locks or close open resources or database connections and so on i personally don't use destructors a lot only when i really need to and have the actual use case for it it is recommended that if you have a resource or database connection open to close it as soon as you're done working with them and as soon as you no longer need them just in case you have a long run in script because if you have a long run in script and you don't close the connection as soon as you're done using it it's going to keep that connection open until the script finishes running so unless you have a good use case for destructors i would try to stay away from them and close your connections as soon as you're done using them couple of things to know about destructors is that if you use exit statement to terminate your script you will still call the destructor so if i refresh the page here it's going to print destruct transaction 1 which means the destructor ran but it's not going to print the amount because we exited here another thing to know about destructors is that if you put the exit statement inside the destruct method whenever this specific destruct method runs no other destruct methods will run on other classes which can cause some issues if you're performing some actions and relying on those methods to run that are within the destructors of other classes before we finish this lesson i want to talk a little bit about php's std class that can be used to create generic objects and also some functions return instances of std class so for example let's say that we have a json string something like this and then we json decode this into an array so we use a built-in function called json the code we pass the string and we pass the second parameter as true to return it as an associative array if we then var dump array we refresh the page we get the array however if you don't pass the second parameter here and just use json decode we refresh we get an object which is an instance of std class and the keys of the array or the keys of the json will become the properties of the class and the values will become the values of those properties so now you're able to access those properties using the object operator so we would use object operator and then a and this should print one and if we do c this prints three and so on you can create custom object by using the std class itself so you could do new std class and then set the properties the way you would set a public properties on your own custom class so you would do object a equals one object b equals to and then we carry bar dom object and refresh we see that it has a and b now let's see how the casting works so let's say we have an array that just contains one two and three as elements and this is numerically indexed rate so this is at the zeroth index this is at one and this is a two we can cast things to object by using the regular casting and just specifying the object as the type so let's do var dump object array and this is going to convert array into object and if we refresh we get the keys as the properties again which is 0 1 and 2 and we're able to access them so let's assign this to a variable object and then here we can do object and we would not do one like this it would not work you have to surround this with brackets and now it will work if we access the index one that is the second element so it should be two and it is two and if we access the first element it will be one now let's cast some other types let's cast integer to object if we refresh we're going to get an object with the scalar as the property and the value whatever the value we're casting and if we were to access that if we set this to object we can access that by using scalar as the property and this will work same applies to booleans so basically any scalar value will be converted to object this way and you will have the property scalar with that value that includes integer floats strings and booleans the null value is cast to object as an empty object so if we refresh we get an empty object without any properties so this is it for this video thank you so much for watching please give this video a thumbs up share and subscribe if you enjoyed it and i'll see on the next video where we're going to talk about some new php 8 features that are related to the things that we talked today such as constructor property promotion and null safe operator
Info
Channel: Program With Gio
Views: 6,777
Rating: undefined out of 5
Keywords: php, php8, php tutorial, php course, learn php the right way, object oriented php, php in 2021, advanced php course, php oop tutorial for beginners full, php classes and objects, php constructor, php destructor, php stdclass, php properties and methods, create classes and objects in php
Id: 6FW72q5fIx8
Channel Id: undefined
Length: 21min 14sec (1274 seconds)
Published: Mon Mar 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.