【问题标题】:How do you reference another parameter as the default value of a parameter in a function?如何引用另一个参数作为函数中参数的默认值?
【发布时间】:2019-04-14 11:58:25
【问题描述】:

下面,如果当前文件名与giveClassActive() 的第一个参数匹配,我有一个函数调用,它为列表项之一提供active 类(来自Bootstrap)。每个列表项都有要显示的文本、要指向的页面的 href 以及要检查的文件名。只有有时$href$file 的值不同,因为# 必须变为%23。所以,我想给$href 一个默认值$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'); 
?>

我的问题是:如何在函数定义中引用另一个参数?

我试过了

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

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

生产的

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

注意:输出为

暂停后编辑

我的问题与PHP function with variable as default value for a parameter 不同,因为该问题不涉及引用参数,而是涉及另一个变量。

【问题讨论】:

  • 关于骗子的注意事项:不一定是相同的问题 - 但相同的解决方案 使其成为骗子

标签: php default-value function-definition


【解决方案1】:

最好的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-03
    • 2017-02-03
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2015-10-27
    • 2019-09-11
    相关资源
    最近更新 更多