【问题标题】:PHP Fatal error: Declaration of ... must be compatible withPHP 致命错误:...的声明必须与
【发布时间】:2026-02-22 19:15:01
【问题描述】:

我找不到问题。此代码工作多年,但在重置服务器后显示此致命错误。也许你可以帮助我。谢谢

PHP 致命错误:声明 styBoxLoadEventArgs::__construct() 必须与 EventArgs::__construct() 兼容 .../modules/sty/events/styBoxLoadEventArgs.php 第 4 行

代码是:

<?php

class styBoxLoadEventArgs extends EventArgs
{
    public $hide = false;
    public $box;

    public function __construct($box)
    {
        $this->box = $box;
    }
}
?>

这里是 EventArgs 的代码

?php

/**
 * EventArgs
 */
abstract class EventArgs
{

    public $sender, $senderClass, $senderObject, $event;
    protected $items;

    /**
     * Creates new EventArgs object
     */
    abstract public function __construct();

    /**
     * Returns specified item
     * 
     * @param   string      item-name
     * @return  mixed
     */
    public function __get($_name)
    {
        if(!array_key_exists($_name, $this->items)) 
        {
            throw new BasicException("Item '" . $_name . "' not found");
        }

        return $this->items[$_name];
    }

    /**
     * Sets specified item
     * 
     * @param   string      item-name 
     * @param   mixed       value
     */
    public function __set($_name, $_value)
    {
        if(!array_key_exists($_name, $this->items))
        {
            throw new BasicException("Item '" . $_name . "' not found");
        }

        $this->items[$_name] = $_value;
    }

    public function &GetByRef($_key)
    {
        if(!array_key_exists($_key, $this->items))
        {
            throw new BasicException("Item '" . $_key . "' not found");
        }

        return $this->items[$_key];
    }

}

【问题讨论】:

  • EventArgs的构造函数长什么样子?
  • 扩展类时,您的构造方法必须与父类的构造方法相对应。我猜你的父类不接受参数或不同的参数?
  • EventArgs 被定义为一个抽象类。我现在发布代码。也许你有一个想法。 THX

标签: php


【解决方案1】:

当子级重新声明父级已定义的函数时,您必须为该函数保留相同的提示/数据类型。因此,假设EventArgs 在其构造函数中请求一个特定的数据对象(或者在 PHP7 中使用严格的类型提示)。您的孩子还必须指定该数据类型。这是一个例子(编造一个)

class EventArgs
{
    public function __construct(Array $box)
    {
        $this->box = $box;
    }
}

在这种情况下,您的子构造函数还必须请求Array。有一些elaborate reasons for this

【讨论】:

    最近更新 更多