1

I would like to know if there is, in PHP, some magic method that is invoked when a constant doesn't exist. I know __callStatic() is invoked when a static method doesn't exist, but what about constant, is there anything?

<?php
class Pizza
{
   const QTD_PIECES_LARGE = 8;
   const QTD_PEDACO_MEDIUM = 4;
   private $name;

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

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

echo 'The number of pieces of the small pizza is:',Pizza::QTD_PIECE_LITTLE;

?>

I was wondering if there is any magic that I can invoke when the method happens to call this constant that doesn't exist?

Remembering that the code is fake, just to exemplify what I want. And I used google translate

Thanks!

acvitorio
  • 11
  • 1
  • Does this answer your question? [Magic \_\_get getter for static properties in PHP](https://stackoverflow.com/questions/1279382/magic-get-getter-for-static-properties-in-php) – chiliNUT Jan 27 '22 at 23:30
  • Unfortunately not. For attributes and normal methods or static methods I can handle it, in my case it's constant. Some method that is invoked when a constant does not exist in the class. But thanks for the reply. – acvitorio Jan 27 '22 at 23:57
  • I don't think you can on a per-class basis. You could potentially do it by setting the global exception handler and then handling any exceptions. If it's `Undefined class constant` then you could call a function but I don't think there's a way to check which class it was checking for that constant – Rylee Jan 28 '22 at 02:49
  • @acvitorio the answer is "no, this is not possible" – chiliNUT Jan 28 '22 at 03:21

1 Answers1

0

In case of non-static properties, there is __get() magic method. When it comes to static properties, there is no such magic method invoked by a call to the inaccessible method.

Optionally, if you want to find out more about magic methods in PHP, you can read: Magic Methods - PHP Manual.

Hexi
  • 37
  • 1
  • 5
  • Yes, I know __get(), __set(), __call(), __isset(), and the other magic methods, but the real question is how can I handle in a method when a constant that doesn't exist is called, since I have to attribute(__get() and __set()), methods(__call()), static method(__callStatic()) only missing for a constant – acvitorio Jan 27 '22 at 23:27