PHP OOP Methods
Methods are used to perform actions.
In Object Oriented Programming in PHP, methods are functions inside classes. Their declaration and behavior is almost similar to normal functions, except their special uses inside the class.
Lets remind the role of a function.
First we declare the function
Then we call it (Optionally we can send arguments into the function)
Some process is done inside the function
Then we return something from the function (Optional)
How to declare a method?
Let's declare a method inside a Example class to echo out a simple string that we give.
We use public keyword to make the method available inside and outside the class. You will learn more about this in the visibility chapter.
How to call a method?
Result: Hello World
First, we create an object ($example) from the class Example
Next, we call the method echo with -> (object operator) and () (parentheses)
The parentheses contains the arguments as usual
The thing you need to understand is that we call methods on objects, not classes.
Changing a property value using methods
Let's implement the things we learned in the above example to our House class. Now we are going to change the color of the house. For ease all the properties are removed from the House class, except $primaryColor.
By default the color of the house is black. We need to change it to another one.
In this example, we have used $this keyword. The next chapter describes more about it.