Method for Defining Array Constants (array Constants) in PHP

  • 2021-08-03 09:45:28
  • OfStack

In PHP, we can't use const to define array constants directly, but const can define string constants, which can be executed in combination with eval () function. Therefore, we can return an array constant by defining a string constant. Here is the moment when we will witness the miracle!


<?php
class Test
{
 const MY_ARR="return array(\"a\",\"b\",\"c\",\"d\");";
 public function getConstArray()
 {
  return eval(Test::MY_ARR);//eval() Function takes a string as a PHP Code execution
 }
}
$t=new Test();
print_r($t->getConstArray());
?>

In the above code, the getConstArray () function is equivalent to an array constant.


Related articles: