PHP Keywords: function and final

16 February 2019 - 11:38pm

Welcome to my series on every PHP keyword and its usage. Today's items: function and final.

In PHP, the function keyword is used to define a new closure (anonymous function), function or method, depending on where they're used.

Functions

A function is a block of code that can be called multiple times from different areas of your code base. A function is globally accessible, though it may require a namespace.

Functions have a name, a list of parameters and an optional return type. Parameters must have a name, and can have an optional type hint and default value.

Return types and parameter types can be prefixed with a ? to indicate that they may accept/return null as a value. Parameters that have null as the default value will also accept null being passed in.

Usage

<?php
function add(float $first, float $second): float
{
    return $first + $second;
}

echo add(2, 3);

Closures

Closures work the same way as functions, except they're assigned to a variable, and are not globally accessible.

Usage

<?php
$add = function(float $first, float $second): float
{
    return $first + $second;
};

echo $add(2, 3);

Methods

Methods are functions that are attached to either a class or an instance of a class, depending on if it the static keyword is used or not.

A static method can be called on a class or instance of that class with the :: operator. An instance method can be called on an instance with the -> operator.

Usage

<?php
class Math
{
    // This can be called on the class
    static function add(float $first, float $second): float
    {
        return $first + $second;
    }

    // This can be called on an instance of that class
    function multiply(float $first, float $second): float
    {
        return $first * $second;
    }
}

echo Math::add(2, 3);

$math = new Math();
echo $math->multiply(2, 3);

final

The final keyword prevents any class that extends your class from overriding a particular method. This way you can allow others to access the method, without allowing them to change how your class or object behaves if it uses this method internally.

Usage

<?php
class Math
{
    final static function add(float $first, float $second): float
    {
        return $first + $second;
    }

    final function multiply(float $first, float $second): float
    {
        return $first * $second;
    }
}

// This will fail, because add and multiply may not be overridden
class MoreMath
{
    static function add(float $first, float $second): float
    {
        return $first - $second;
    }

    function multiply(float $first, float $second): float
    {
        return $first / $second;
    }
}