dsorecdf78171 2017-06-02 18:21
浏览 316
已采纳

PHP中带有变量参数列表的抽象方法

I came across a question in OOP in PHP. I tried to implement an abstract parent class method and from the child class, I have to use it with a variable number of arguments.

Here is the error thrown :

PHP Fatal error: Declaration of Square::getArea($length) must be compatible with Shape::getArea()

And the classes :

abstract class Shape {
    abstract protected function getArea();
}

class Square extends Shape {

    public function getArea($length)
    {
        return pow($length, 2);
    }

}

class Triangle extends Shape {

    public function getArea($base, $height)
    {
        return .5 * $base * $height;
    }

}

I could use the child's __construct() methods to set the properties of the different shapes at the initiation time but I'd like to know if another way exists and allows me to define variable list of parameters.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douping7975 2017-06-02 19:49
    关注

    As in the comments under your question mentioned, there are several ways to solve your issue.

    Class properties and the constructor That would be the easiest approach in my opinion. It 's easy and smart.

    interface Shape
    {
        protected function getShape();
    }
    
    class Square implements Shape
    {
        protected $length;
    
        public function __construct(int $length)
        {
            $this->length = $length;
        }
    
        protected function shape()
        {
            return pow($this->length, 2);
        }
    }
    
    class Triangle implements Shape
    {
        protected $base;
    
        protected $height;
    
        public function __construct(int $base, int $height)
        {
            $this->base = $base;
            $this->height = $height;
        }
    
        protected function getShape()
        {
            return .5 * $this->base * $this->height;
        }
    }
    

    Every class implements the Shape interface. The getShape method got no attributes. The attributes are protected properties of the class itself. You set these properties when calling the constructor of the specific class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀