PHP OOP Methods
In Object Oriented Programming in PHP, methods are functions inside classes. Their declaration and behavior are almost similar to normal functions, except their special uses inside the class.
Let's 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 class named Example class to echo out a simple string that we give.
<?php
class Example {
public function echo($string) {
echo $string;
}
}
We use the 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?
$example = new Example();
$example -> echo('Hello World');
Result: Hello World
Explained:- First, we create an object ($example) from the class Example
- Next, we call the method echo with -> (object operator) and () (parentheses)
- The parentheses contain the arguments as usual
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.
<?php
class House {
public $primaryColor = 'black';
public function changeColor($color) {
$this -> primaryColor = $color;
}
}
// creates an object from the class
$myHouse = new House();
# black (default value)
echo $myHouse -> primaryColor;
// change the color of the house
$myHouse -> changeColor('white');
# white
echo $myHouse -> primaryColor;
Run Example ››In this example, we have used $this keyword. The next chapter describes more about it.