October 24, 2024
Chicago 12, Melborne City, USA
PHP

PHP: Check if variable satisfies type definition in string


Is there a way to test if a $var satisfies a type defined in a string other than this:

function test_type(mixed $value, string $type): bool 
{
    try { 
          eval('(fn('.$type.' $a)=>true)($value);'); 
          return true;  
    }  
    catch (Throwable  $e) { 
          return false; 
    }
}
test_type(null,  "int") ; // returns false. 
test_type(null,  "?int") ; // return true. 
test_type("hello, world", "bool") ; // returns true. I want it to return false
test_type(new DateTime, "DateTimeInterface") ; // return true. 
test_type(new DateTime, "null|int|DateTime|DateTimeImmutable") ; // return true

There are two major problems with this approach that do not need further explanation:

  • eval
  • automatic type conversion (as in test_type("hello, world", "bool") => true )

Is there a way to avoid these problems? I’ve Googled a lot but haven’t found anything up to now.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video