PHP stand for Hypertext Preprocessor is widely used, generally use as web development. PHP code usually embedded into HTML code and interpreted by a web server with PHP processor module.
PHP can be programmed as Procedural and Object Oriented(OOP). Most likely, tutorial on the internet will teach by using the procedural programming. Most probably, both method will produce the same result if coded in a correct way.
Why OOP? Some might be asking - Why should I start to code in OOP while procedural can do the things without any hiccup? Well I 'll answer it as "Suit yourself, it's your code not mine" if you asked me personally. But if you asked me reason on why I write mostly in OOP approach. The answer then is "I just want to keep myself DRY". DRY in programming world mean Don't Repeat Yourself. If you do read tutorials of tips on programming, you will probably heard this term DRY. Class and Object will make yourself DRY, so does procedural will make yourself WET?
To start doing OOP in PHP, the main things that we should have in mind is Class and Object. To have an object, we need class which will be the object templates. So before we start doing or messing with object, we need to create class. Below is an example of User class definition. The file below should be name as "User.php".
From the User class definition, you can see that my variable is all in private while my methods/functions are mix with public and private. Generally, a private variable or function can only be access inside the class definition. Which mean, if I want to set $_username value from outside of the class User brackets, I need a method to pass the value. In above code, all the variable got their public set and get method which accessible on public. Some function and method are kept private as we do not want it to be change or access from public. By practice to keep public as minimal as possible, we also did protect the object from unnecessary change from public or outside script.
How to use object when we do have the class? To declare object from our class, the syntax is simple, below is a file with PHP code that make use of above User class.
The files above will show basic syntax on how you can code in OOP approach. Below is my Connection.php files that I used to link my PHP with MySQL just incase you having issue on missing include file.
I hope this post will benefit you in some way. Please consider to like this post on Facebook by clicking on FB like button below my post title. Leave a comments if you need explanation or help.