PHP: Functions I

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Functions I

Aims:

Revision of functions

Defining functions versus invoking functions

Example: defining a function for computing $x2

function square( $x )
{
    return $x * $x;
}

Observations

Observations

Class exercise: what is the output of the following?

<?php
    function square( $x )
    {
        return $x * $x;
    }   
    
    echo '<table>';
    $y = square(1);
    echo '<tr><td>1</td><td>' . $y . '</td></tr>';
    echo '<tr><td>2</td><td>' . square(2) . '</td></tr>';   
    echo '<tr><td>3</td><td>' . square(2 + 1) . '</td></tr>';
    echo '<tr><td>4</td><td>' . square( square(2) ) . '</td></tr>';
    $z = 5;
    echo '<tr><td>5</td><td>' . square($z) . '</td></tr>';
    echo '</table>';
?>

Formal parameters and actual parameters

Class exercise

The return statement

Pointers for advanced students