Marvin
Marvin

Reputation: 953

How do you reference another parameter as the default value of a parameter in a function?

Below, I have a function call that gives one of the list items the active class (from Bootstrap) if the current filename matches the first argument of the giveClassActive(). Each list item has text it will show, an href for the page to direct to, and a filename that it is checking for. Only sometimes are the $href and $file values different because # must become %23. So, I want to give the $href a default value of $file.

<?php
function giveClassActive($file, $href, $show) {
    echo '<li class = "';
    $filename = explode('/', $_SERVER['SCRIPT_NAME']);
    $file_name = end($filename);
    if ($file_name == $file) {
        echo 'active';
    }
    echo '">';
    echo '<a href = "' . $href . '">' . $show . '</a></li>';
}
giveClassActive('calculator #5.php', 'calculator %235.php', 'Calculator');
giveClassActive('contact.php', 'contact.php', 'Contact'); 
?>

My question is: How do I reference another parameter in a function definition?

I have tried

function giveClassActive($file, $href = $file, $show) {

and

function giveClassActive($file, $href = this.$file, $show) {

which produce

Fatal error: Constant expression contains invalid operations in C:\Bitnami\wampstack-7.1.22-1\apache2\htdocs\LarryUllman\Chapter 3\includes\header.html on line 20

Note: The output is

Output

Edit after put on hold

My question is different from PHP function with variable as default value for a parameter because that question does not ask about referencing a parameter, but rather another variable.

Upvotes: 1

Views: 177

Answers (1)

Marvin
Marvin

Reputation: 953

Best is

if ($href == null)
    $href = $file;

Upvotes: 0

Related Questions