-3

The issue is quite simple. I need to return multiple values from a function. How can I do it?

Code is below:

<?php
    abstract class Products
    {
        protected $name;
        protected $price;

        public function __construct($name, $price)
        {
            $this->name = $name;
            $this->price = $price;
        }

        public function getName()
        {
            return $this->name;
        }

        public function getPrice()
        {
            return $this->price;
        }
    }

    // A new class extension

    class Furniture extends Products
    {
        protected $width;
        protected $height;
        protected $length;

        public function getSize()
        {
            // return $this->width;
            // return $this->height;
            // return $this->length;
            // return array($this->width, $this->height, $this->length);
        }
    }

So as far as I understand, when I return something, it will stop the function, so I understand why I can't just do return three times. An attempt to return an array didn't work. It resulted in an error:

Notice: Array to string conversion

How can I return all three of those?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

2

If you change your function to return an array like so:

class Furniture extends Products
{

    protected $width;
    protected $height;
    protected $length;

    public function getSize()
    {
        return [
            'width' => $this->width,
            'height' => $this->height,
            'length' => $this->length
        ];
    }
}

You can then access your data like so:

$furniture = new Furniture;
$size = $furniture->getSize();

$height = $size['height'];

Returning multiple data values by an array is a pretty common thing. Another method would be to use a stdClass, which would pretty much have the same outcome in this case.

yivi
  • 42,438
  • 18
  • 116
  • 138
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23