What is a method? In PHP, it’s just a function inside of a class. That’s the easiest way to think about it. You initialize them the exact same way that you would a function, including using the function keyword.
PHP – P35: User Defined Functions
In object oriented programming, objects can have specific characteristics, but they can also perform specific actions. The actions are represented by methods. Methods can also have visibility modifiers, such as private, protected, and public, but we’ll leave those out of this article and stick to the default public modifier.
We’re building on from our previous article and adding methods to the Dog and Car classes.
PHP- P45: Class Constants – NEEDS LINK
Some methods are declared with parameters (optional params) and others without; we will cover both. Where are methods placed? Usually right after the properties in a class. The constants stick to the top of the class, followed by properties, followed by methods. Can they be placed in a different order? Of course, however, per convention we place them after the properties.
Creating a Method
Methods are defined as follows:
<?php
modifier function method_name($optional_param) {
echo "Method Body";
}
The modifier refers to the keywords public, private, or protected. We’ll focus on the public modifier only in this article. Frankly, the public keyword can be omitted since the default modifier is public, but we’ll include it for best practice.
<?php
public function method_name($optional_param) {
echo "Method Body";
}
Now that we know how to create a method, let’s start implementing it into our Dog class. The first method that we’ll define is the method walk(). This method will not have any parameters and will just echo out a statement.
<?php
class Dog {
const HAS_HEART = true;
const HAS_TAIL = true;
public $eye_color = "Brown";
public $dob = "January 30, 2017";
public $does_shed = true;
public $kingdom = "Animalia";
public $phylum = "Mammalia";
public $class = "Mammalia";
public $order = "Carnivara";
public $family = "Canidae";
public $genus = "Canis";
public $species = "Canis Lupus";
public $subspecies = "Canis Lupus Familiaris";
public $breed = "German Shepherd Dog";
public $fur_color = "Black and Tan";
public function walk() {
echo "I'm walking";
}
}
To call a method, we have to first instantiate the object. In this case, let’s create a Dog object and call our walk method.
<?php
$dog = new Dog();
$dog->walk();
The $dog object will reply with “I’m walking.” Another action that dogs perform regularly is barking, so we can create a bark() method.
<?php
class Dog {
public function bark() {
echo "I'm barking";
}
}
$dog = new Dog();
$dog->bark();
When we call the method, it will echo out “I’m barking.”
Methods with Parameters
Now that we saw a couple of examples of methods without parameters, let’s take a look at one with a parameter. A good one would be sleep(). A dog may go to sleep based on the amount of energy it has, so we’ll declare an $energy_level parameter inside of the parentheses of our sleep() method.
public function sleep( $energy_level ) { }
When we instantiate our object, we can pass the dog’s energy level as an argument to the sleep method. Within the body of the sleep method, we’ll create an if statement that checks the argument that it just received and output either that it’s sleeping or that it doesn’t want to sleep.
<?php
class Dog
public function sleep( $energy_level ) {
if ( $energy_level < 40 ) {
echo "I'm sleeping";
} else {
echo "I don't want to sleep";
}
}
}
$dog = new Dog();
$dog->sleep( 20 );
If we pass 20 as the argument, we’ll get a response that the dog is sleeping.
Default Parameter Values
We can also declare a default value for the $energy_level parameter. To declare the default value of a parameter, just add the equal sign and the parameter value after the parameter declaration.
<?php
class ClassName {
modifier function method_name( $parameter = $value ) {
echo "Method Body";
}
}
For our sleep() method, we’ll set the default value of the $energy_level to 100. Why would we want to do that? Because we can now call the method without passing any arguments to it.
<?php
class Dog
public function sleep( $energy_level = 100 ) {
if ( $energy_level < 40 ) {
echo "I'm sleeping";
} else {
echo "I don't want to sleep";
}
}
}
$dog = new Dog();
$dog->sleep();
$dog->sleep(30);
In the first example without any argument passed, the output will be “I don’t want to sleep.” The second time that the sleep() method is called, and 30 is passed as an argument, the output will be “I’m sleeping.”
Car Actions
Let’s think about actions that a car can perform. Three that come to mind is turn-on, turn-off, and drive. Turning on and off the car is pretty straight forward. We could check to see if the key is inserted, but to keep the examples light, we’ll skip it in this instance.
<?php
class Car {
const HAS_HEADLIGHTS = true;
const HAS_TAIL_LIGHTS = true;
const HAS_TURN_SIGNALS = true;
public string $color;
public string $make;
public string $model;
public int $year;
public int $fuel_type = 93;
public int $hp;
public int $tq;
public string $transmission = "6 Speed Manual";
public string $vehicle_type = "Coupe";
public float $exterior_height;
public float $exterior_width;
public float $exterior_length;
public string $exterior_um = "in";
public float $weight;
public string $weight_um = "lbs";
public function turnOn() {
echo "I'm on";
}
public function turnOff() {
echo "I'm off";
}
}
$lamborghini = new Car();
$lamborghini->color = "Black";
$lamborghini->make = "Lamborghini";
$lamborghini->model = "Diablo";
$lamborghini->turnOn();
$lamborghini->turnOff();
In the example above, we created two methods: turnOn() and turnOff(). A new Lamborghini was constructed and the car was turned on and turned off. The output of the above program will be: “I’m on” followed by “I’m off.”
Let’s look at how we would construct the drive() method. The default state of the vehicle will be off. In order to drive our Lamborghini, we’ll have to turn it on first.
<?php
Class Car {
public function drive( $is_car_on = false ) {
if ( $is_car_on ) {
echo "I'm driving";
} else {
echo "You gotta turn me on";
}
}
}
$lamborghini = new Car();
$lamborghini->color = "Black";
$lamborghini->make = "Lamborghini";
$lamborghini->model = "Diablo";
$lamborghini->drive();
$lamborghini->drive( true );
Below our class, we create a new Lamborghini Diablo. We attempt to drive it without passing any arguments to the drive() method, but we get the following response, “You gotta turn me on.” On our next attempt, we pass the true boolean value to our drive() method and we get the response that we were looking for, “I’m driving.” When we pass an argument to a method that has a default parameter value, the value is overwritten and the argument always wins.
These have been oversimplified examples, but I believe you get the point of what methods actually are now.