【问题标题】:What is a parameter signature in PHP?PHP中的参数签名是什么?
【发布时间】:2013-04-25 16:18:39
【问题描述】:

PHP 官方文档在解释类和对象部分下的 extends 时说:

"When overriding methods, the parameter signature should remain the same or PHP
will generate an E_STRICT level error. This does not apply to the constructor
which allows overriding with different parameters."

所以我想知道,参数签名是什么?

文档中的示例如下:

<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?> 

官方在线link

【问题讨论】:

    标签: php parameters signature


    【解决方案1】:

    参数签名只是方法定义(签名)中参数的定义。引用文本的意思是,在覆盖父类的方法时使用相同数量(和类型,在 PHP 中不适用)的参数。
    函数/方法的签名也称为head。它包含名称和参数。函数的实际代码称为body

    function foo($arg1, $arg2) // signature
    {
        // body
    }
    

    因此,例如,如果您在父类中有一个方法 foo($arg1, $arg2),则不能通过定义方法 foo($arg) 在扩展类中覆盖它。

    【讨论】:

    • 不管文档怎么说,它可以像那个兄弟一样被覆盖。试试看。
    • @Raidenace 那么 taht 将是一种不同的方法,而不是父类中方法的扩展。
    • 没有。如果你的父类有function displayVar(),子类有function displayVar($x),那么调用childObj-&gt;displayVar() 应该调用父类displayVar(),不带参数,因为根据你的说法,这是一种不同的方法。但这不是 PHP 的行为方式。
    • @Raidenace,不,它会触发错误Declaration of ChildClass::displayVar() should be compatible with that of SimpleClass::displayVar()
    • 你试过了吗?而且它也不应该触发该错误,因为它们是两个签名,因此是两个不同的功能,不是吗?
    猜你喜欢
    • 2022-06-28
    • 2011-01-29
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多