sevenTopo's avatar

Unit Test : Access child properties from parent class

Hi Folks !

I have a situation here related to PHP OOP...im trying to write unit test for the class TypeAlert.php bellow :


final class TypeAlert extends Enum
{


    const INFO      =   0;
    const SUCESS    =   1;
    const WARNING   =   2;
    const ERROR     =   3;



}

In the other hand i have the parent class defined as bellow Enum.php:

use App\Enums\Exceptions\EnumNotFoundProperty;
abstract class Enum  {

   
        public static function __callStatic(string $name, array $arguments)
        {
            
            if(defined(static::class."::$name"))
                {
                    return static::$$name;
                }
                

            throw new EnumNotFoundProperty($name);
                
        }

      
}

when i run the unit test the console says that im tryin to Access undeclared static property App\Enums\TypeAlert::$WARNING (For example)....what's wrong with my code ?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Your const doesn't have a $, so return static::$$name; why the double $$?

Also, why are you trying to fetching constants using __callStatic at all?

In any case, I would probably use the constant function instead

public static function __callStatic(string $name, array $arguments)
{
    $constant = sprintf('%s::%s', static::class, $name);
    if(defined($constant)) {
      return constant($constant);
    }

    throw new EnumNotFoundProperty($name);
  }
1 like
sevenTopo's avatar

Hi @tykus ; thank you for replying and your help ; actually i fixed that using const() function ...and it works using the $$ ;

im using $$ cause my const for ex $name = "info" is just a string so i should concatenate this value to $ just to be a variable .

__callStatic it's exactly what i need .

Thank you again

Please or to participate in this conversation.