user10560159
user10560159

Reputation:

Class name must be a valid object or a string

I am trying to inject one class (a simple PHP class) into another (an ORM\Entity annotated class), and getting an error, but I cannot discover the source. Looking at the code I feel like I am doing everything correctly, yet I cannot solve this error.

Here is the relevant code:

First, the class ORM\Entity where I want to inject the ErrorConstants class:

use Base\Model\Constants\ErrorConstants;

/**
* @ORM\Entity ...
*/
class CwPackagePeriod extends AbstractRestEntity
   public $errors;

   public function __construct()
   {
      parent::__construct();

      $this->errors = new ErrorConstants();
   }
}

The ErrorConstants class is a simple class that contains a list of error constants:

class ErrorConstants
{
    public const ERR_MISSING = 'Record could not be found.';
}

The error occurs when I try to throw an exception in the CwPackagePeriod class if an integer value is out of bounds on a setter:

throw new InvalidOrMissingParameterException(
   sprintf($this->errors::ERR_MISSING)
);

The error is the following:

Class name must be a valid object or a string

The AbstractRestEntity class does not contain any reference to ErrorConstants, and when I add the reference there, nothing changes with respect to the error. What am I doing wrong?

Upvotes: 0

Views: 2809

Answers (1)

iiirxs
iiirxs

Reputation: 4582

As u_mulder noted constants refer to class, not to class instance. In order to properly get the constants from your class you could use something like that in your ErrorConstants class:

public function getConstants()
{
    $reflectionClass = new \ReflectionClass($this);
    return $reflectionClass->getConstants();
}

then in your CwPackagePeriod class:

public function __construct()
{
    parent::__construct();
    $errorConstants = new ErrorConstants();
    $this->errors = $errorConstants->getConstants();
}
...
throw new InvalidOrMissingParameterException(
   sprintf($this->errors['ERR_MISSING']);
);

Of course the simplest solution would be to use just:

throw new InvalidOrMissingParameterException(
   sprintf(ErrorConstants::ERR_MISSING);
);

Finally I would like to note, although it is not very intuitive, you CAN indeed use $this->errors::ERR_MISSING to get a constant. The reason because you get this error is probably because $this->errors is not defined in that part of code for some reason.

Upvotes: 1

Related Questions