This is an Object-oriented PHP Tutorial, we will briefly cover how to use classes and objects so most will understand it, and how to use OOP in real situations.
OOP can sometimes be useful if you have a block of code, that you would otherwise have to repeat a lot of places, across multiple files or projects.
In situations where you have a lot of repeated database connections, such as across multiple files, it can be a good idea to make a function, and then simply call that whenever you need to connect to the database. But when you also got a lot of database queries, it may be a good idea to simply group all the functions together in a single class.
OOP is about maintainability and scalability. OOP makes it easier to maintain larger projects and to reuse code in other files and projects.
Classes and Objects in PHP
A class in PHP is a template used to create objects. Classes can include Properties and Methods (variables and functions).
OOP PHP Properties Example
The below is a simple PHP class, containing two variables.
class MyClassName {
public $Property1 = 'Hallo hallo!';
public $MyVariableName = 'Hallo dude!'; // Another Property
}
To access these variables, we first need to create an object, which is basically just en instance of the class.
$MyObject = new MyClassName(); // Creates an object from the class
We can then output or change the variable values as we wish.
echo $MyObject->Property1 ."<br>";
$MyObject->MyVariableName = 'My House'; // Changes the variable value
OOP PHP Methods Example
You can also include functions in your classes, when this is done the functions are referred to as methods. A simple method that everyone should be able to understand is shown below.
class MyClassName {
function SayHallo() {
return 'Hallo';
}
}
$MyObject = new MyClassName();
echo $MyObject->SayHallo();
No comments:
Post a Comment