Question

I'm working on a PHP class that I wrote. Its setColour() method typehints for an instance of another class of mine, Colour.

I'm doing this:

$colour = new Colour($updates->colour);
echo get_class($colour);
$product->setColour($colour);

As I'd expect, the get_class tells me that $colour is an instance of domain\Colour, but I then get an error when passing it to setColour():

Catchable fatal error: Argument 1 passed to domain\Product::setColour() must be an instance of domain\Colour, string given,…

Colour looks like this:

<?php
namespace base\domain;

/**
 * Represents a colour.
 *
 **/
class Colour extends \base\domain\Enum {
const __default = self::NONE;

const NONE = NULL;
const BLACK = 'black';
const BLUE = 'blue';
const BRONZE = 'bronze';
const BROWN = 'brown';
const GOLD = 'gold';
const GREEN = 'green';
const GREY = 'grey';
const MULTICOLOURED = 'multicoloured';
const ORANGE = 'orange';
const PINK = 'pink';
const PURPLE = 'purple';
const RED = 'red';
const SILVER = 'silver';
const WHITE = 'white';
const YELLOW = 'yellow';

} // END class Colour

Colour extends a custom Enum type, which overrides __toString(), so I thought that might be causing the problem, but when I removing the __toString() implementation doesn't help.

Any thoughts you can offer would be much appreciated.

Was it helpful?

Solution

I make a test, i don't see any problems:

<?php

class Colour {

    private $name;

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

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

}

class Product {

    public $colour;

    public function setColour(Colour $c) {
        $this->colour = $c;
    }

}

error_reporting(E_ALL);
$product = new Product();
$colour = new Colour('red');
echo get_class($colour).' ';
$product->setColour($colour);
echo $product->colour;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top