Arguments

A default value is a constant, and defaults go at the end.

An argument with a default goes at the end of the list: function greet($name, $title = 'user'). A call with one argument substitutes user. A required argument after an optional one is confusing, and in PHP 8 it is already a style error you are better off not learning.

The default is not a "live formula" evaluated when the argument is skipped: it must be a constant expression. You cannot put a function call or new there. A fallback string or number is fine.

An array is passed as a copy unless there is &. Changing the local copy does not change the caller's array. A & reference is rarely needed: it gives one value two names and makes code harder to read. Return a new array if the result is a different collection.

Extra arguments to a user-defined function are an error in modern PHP, not a quiet tail. Named arguments such as clamp(n: 1, lo: 0, hi: 9) read well at a call site with several numbers in a row. In a short task positional ones are enough.

Practice

  1. Where the default goes

    A function has two parameters, and the second may be omitted. Where does it belong?

    • At the start of the list
    • At the end of the list
    • Inside echo
    • Only in a constructor
  2. What gets substituted

    function label($name, $title = 'user'). The call is label('Ann'). What second argument does the function get?

  3. A label

    Write function label($name, $title = 'user'). Return the string title:name, for example user:Ann.